# deepset AI Platform Documentation > Everything you need to build with deepset. This file contains all documentation content in a single document following the llmstxt.org standard. ## FAQ overview # FAQ Find answers to common questions, including topics that often come up with support. ## Available FAQs {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## Why Is There a Spike in Indexing Tasks? An increased number of indexing tasks for an index may be caused by metadata updates. Each metadata change on a file in queues work on the index. A large batch of edits produces a large batch of tasks. That is expected behavior, not a fault in the system. *** ## What You Might Notice - The Indexes page shows more pending or running tasks right after you change metadata on files. - A bulk metadata update across many documents causes a sharp rise in the task count. ## How It Works - Changing metadata on a single document creates one indexing task for that document. - Applying the same metadata change across many documents creates one task per affected document. The index pipeline picks up these tasks and applies them in order. While work is still in the queue, the task count stays higher than usual. ## What to Expect Tasks finish as the index catches up. The pending task count drops on its own when processing completes. You don't need to take action unless something stays stuck for an unusually long time and you have ruled out a large metadata change as the cause. ## Tips If the task count spikes and you are unsure why, check whether a script, integration, or teammate recently ran a bulk metadata update before you open a support ticket. ## Related Documentation - [Indexes](https://docs.cloud.deepset.ai/docs/indexes) --- ## Why Is SSO Login Not Working? # Why Is My SSO Login Not Working? Users can't sign in to through SSO configured with Microsoft Entra ID. The Entra ID admin can log in, but other users can't. The cause is that the application in Microsoft Entra ID hasn't been granted the required scopes to read user profiles. *** ## Symptoms - The SSO login process gets stuck at the redirect from Microsoft Entra ID back to , and authentication doesn't complete. - The Entra ID admin can authenticate without issues, but non-admin users can't. ## Cause The application in Microsoft Entra ID needs permission to access user profiles. Without this consent, the authentication flow fails at the redirect step. Entra ID admins bypass this restriction, which is why they can log in while other users can't. ## Resolution 1. Ask your Microsoft Entra ID admin to sign in to the [Microsoft Entra admin center](https://entra.microsoft.com). 2. Go to **Enterprise applications** > **All applications** and find the application. 3. Select **Permissions** under **Security**. 4. Select **Grant admin consent** to approve the required scopes, specifically the scope for accessing user profiles. 5. Ask a non-admin user to test the SSO login to confirm the issue is resolved. ## Verification After the Entra ID admin grants consent, ask a non-admin user to log in to through SSO. A successful login confirms the issue is resolved. --- ## Does Deleting Files from Haystack Enterprise Platform Remove Job Results # Does Deleting Files from Remove Job Results? No. Deleting files from doesn't remove completed job results. Files and job results are different entities in the infrastructure. You can safely delete files after a job completes and still access the output. *** ## How It Works When you run a job, stores the results separately from the source files. Removing the source files after a job completes doesn't affect the job output. You can still view and download the results from the **Jobs** page. ## Related Documentation - [Jobs](https://docs.cloud.deepset.ai/docs/about-jobs) --- ## Search History and Pipeline Log Retention in Haystack Enterprise Platform # What's the Retention Policy for Search History and Pipeline Logs? stores two types of data relevant to privacy and compliance reviews: search history and pipeline logs. Check the data retention policy for each type. *** ## Search History Retention stores search history until you delete it or ask deepset Support to remove it. There is no automatic expiry. You can delete your search history at any time from within the platform. ## Pipeline Log Retention Pipeline logs capture activity from your pipeline infrastructure. These logs are accessible to you for two days after they are generated. deepset retains them in the backend for two weeks before they are removed. ## Tips If your organization has specific data retention requirements, take these steps: - Delete search history proactively from within the platform rather than waiting for a support request. - Factor the two-day access window into any monitoring or audit processes that rely on pipeline log data. --- ## Does Haystack Enterprise Platform Train on Customer Data? # Does Train on Customer Data? does not use customer data to train AI models. This article is for organizations that need to confirm this policy as part of a privacy review or data protection assessment. *** ## Data Training Policy deepset does not use customer data to train, fine-tune, or improve AI models. What you upload and process in is used only to run your pipelines. ## Tips For formal documentation of how deepset handles your data, ask your deepset account team for the relevant data processing agreement or privacy documentation. --- ## API Documentation API endpoints are grouped into two main collections: - [Main API](./main/haystack-enterprise-platform): Core features and feedback endpoints. - [Jobs API](./jobs/jobs): Job management endpoints. ## Structure and Organization API uses REST-based architecture to offer intuitive and predictable structure. The URLs are structured to be resource-oriented and easy to understand. The API returns JSON responses using standard HTTP response codes. The API uses the standard HTTP verbs to act on resources: - `GET`: Retrieves information from the resource. - `PUT`: Updates or replaces a resource. - `POST`: Creates a resource. - `DELETE`: Deletes a resource. - `PATCH`: Updates a specific characteristic or part of a resource. ### Response Schema REST API follows the [OpenAPI schema standard](https://swagger.io/specification/). While core properties are consistently present in responses, some keys are optional and depend on your data and pipeline configuration. This is especially true for the `answers[]` and `documents[]` arrays. The `answers[]` array is always present in the [Search](./main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) endpoint response, but the `meta` objects within it may vary. For instance, they may contain a `_references[]` array in some responses, while being empty in others, depending on your content structure. Always check if a property exists before accessing it and implement thorough data validation to make sure your code stays robust across different response structures. ### Base URLs The base URL for deployments is `https://api.cloud.deepset.ai/`. All endpoints, except for [Health](./main/health-health-get.api.mdx), additionally use the `api/v1/` prefix before the resource name, for example: `https://api.cloud.deepset.ai/api/v1/users/`. ### Authentication Machine-to-machine authentication is done using an API key that you can generate in the UI. Each API token is a Jason Web Token ([JWT](https://jwt.io/)), a signed token whose signature can be verified using a key. For more information, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). The API key inherits the permissions of the user who created it. This means that if an Admin user creates an API key, the key has the same permissions as Admin. ## Change management policies regarding changes to the API, including the addition of new features, modifications to existing endpoints, and the deprecation process. ### Changes to Endpoints #### Adding Fields may add new fields to existing endpoints at any time without prior notice. These additions are not considered breaking changes. To ensure smooth operation, design your applications to handle unexpected fields gracefully. #### Modifying or Removing Fields If we plan to modify or remove existing fields, we will: - Notify you through the newsletter. - Support both the old and new behaviors for at least two months before fully implementing the change. #### New Endpoints New endpoints may be labeled as "beta." This means they may be unstable, and we don't recommend using them in your production scenarios until the label is removed. ## Deprecation Policy When an endpoint is scheduled for removal, we will: - Mark it as deprecated in the documentation. - Announce the deprecation through the newsletter. - Maintain the deprecated endpoint for two months after the announcement date. ## Stay Informed Subscribe to the newsletter for timely updates and review this documentation for the latest information. ## Pagination, Timeouts, and Date-Time Format ### Pagination API uses pagination to divide a large set of entities into separate pages, enhancing response times. Endpoints use either page-based or cursor-based pagination. Sometimes both options are possible but you can't use them at the same time. When a request involves pagination, the API provides details about the total number of items available. In page-based pagination, you specify the desired page and the number of items per page by using the `page_number` and `limit` query parameters. For example, to view 20 evaluation sets on page 2, your request would be as follows: ```curl curl --request GET \ --url 'https://api.cloud.deepset.ai/api/v1/workspaces/default/evaluation_sets?limit=20&page_number=2' \ --header 'accept: application/json' \ --header 'authorization: Bearer ``` To retrieve more files, make another request with updated pagination parameters. If you're using a script or app, iterate through the pages until you retrieve all the items or reach the desired number. In cursor-based pagination, you can use the `before` or `after` parameter to view items preceding or following a specific item ID. For instance, to display 10 evaluation sets preceding the one with ID ab61f0cd-316a-4c66-879f-65dbe28ced1e, include this ID in the before parameter as shown below: ``` curl --request GET \ --url 'https://api.cloud.deepset.ai/api/v1/workspaces/workspace_name/evaluation_sets?limit=10&before=ab61f0cd-316a-4c66-879f-65dbe28ced1e' \ --header 'accept: application/json' \ --header 'authorization: Bearer ``` ### Date-Time All date-time values are in the UTC time in the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, which follows the convention: `YYYY-MM-DDTHH:MM:SS.sssZ`, where: - `YYYY` is the year - `MM` is the month - `DD` is the day - `T` is the delimiter that separates the date from time - `HH` is the hour in a 24-hour clock format - `MM` is minutes - `SS` is seconds - `.sss` is fractional seconds, can be one or more digits, represent a decimal fraction of a second - `Z` is a suffix that indicates that the time is in UTC. For example, `2023-04-25T07:37:58.326042Z` represents 25th April 2023, 7:37 and 58.326042 seconds in UTC. ### Timeouts The timeout for search is 2 minutes. The timeout for other requests is 3 minutes. ## Status and Error Codes API uses standard HTTP status codes. Here's a summary of the codes most often used. ### Success Messages | Code | Meaning | Possible Reasons | | :--- | :------------------- | :---------------------------------------------------------------------------------------------------------------------------------- | | 200 | Successful response. | Everything worked OK. | | 201 | Created. | A resource was successfully created or added. | | 202 | Accepted. | The request is accepted for processing but the processing is not yet finished. | | 204 | No content. | The request was successfully processed and is not returning any content. One reason could be the successful deletion of a resource. | ### Client Errors | Code | Meaning | Possible Reasons | | :--- | :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | Bad request. | A missing required parameter or wrong syntax. | | 401 | Unauthorized. | An invalid API key was provided. | | 403 | Forbidden. | A missing or invalid API key. | | 404 | Not found. | The resource doesn't exist. | | 406 | Not acceptable. | The resource can only create content that is unacceptable in the response. | | 408 | Request timeout. | The server waited too long for the request. | | 409 | Conflict. | A resource already exists. | | 412 | Precondition failed. | Check the details in the response. Possible reasons could be that is missing the required permissions to connect to the infrastructure, a resource is being used, a pipeline wasn't deployed. | | 413 | Payload too large. | The data being uploaded exceeds the size limit. The size limit is 200 MB for files and 32766 bytes for metadata, and 256 KB for pipeline YAML configuration. | | 415 | Unsupported media type. | doesn't support the format of the data being uploaded. For supported formats, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). | | 422 | Content that cannot be processed. | The request was correctly formed but couldn't be processed because of semantic errors. | | 424 | Failed dependency. | The request failed because it depends on another request, which also failed. | ### Server Errors | Code | Meaning | Possible Reasons | | :--- | :--------------------- | :------------------------------------------------------------------------------------------------------------------------------ | | 500 | Internal server error. | The server encountered a situation it doesn't know how to handle. | | 591 | Pipeline on standby. | The pipeline wasn't used for a while and was put on standby to save resources. Wait a while until it's activated and try again. | You can check the full list of codes at [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status). ## Resource IDs Some API endpoints use resource IDs instead of names. For example, to list workspace integrations, you need the workspace ID. You can find IDs either by calling a REST API endpoint or by checking them in the UI. ### Finding IDs in the UI You can copy all IDs directly from the platform interface. #### Workspace ID 1. Click your profile icon. 2. Go to *Settings > Workspace > General*. #### Organization ID 1. Click your profile icon. 2. Go to *Settings > Organization > General*. #### Pipeline ID 1. Click **Pipelines**. 2. Find the pipeline you need and click its name. This opens the Pipeline Details page, where the ID appears right below the pipeline name. #### Index ID 1. Click **Indexes**. 2. Find the index you need and click its name. This opens the Index Details page, where the ID appears right below the index name. #### Job ID 1. Click **Jobs**. 2. Find the job you need and click its name. This opens the Job Details page, where the ID appears right below the job name. ### Finding IDs with API Endpoints Each resource type has a dedicated endpoint that returns its ID. - To get an organization ID, use the [Get Organization](/docs/api/main/get-organization-api-v-1-organization-get.api.mdx) endpoint. - To get a workspace ID, use the [Get Workspace By Name](/docs/api/main/get-workspace-by-name-api-v-1-workspaces-workspace-name-get.api.mdx) endpoint. - To get a pipeline ID, use the [Get Pipeline](/docs/api/main/get-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-get.api.mdx) endpoint. - To get an index ID, use the [Get Index By Name](/docs/api/main/get-index-by-name-api-v-1-workspaces-workspace-name-indexes-index-name-get.api.mdx) endpoint. - To get a job ID, use the [Get Jobs](/docs/api/jobs/get-jobs-api-v-2-workspaces-workspace-id-jobs-get.api.mdx) endpoint. --- ## Create Job Creates a job. --- ## Create Shared Job Creates a link to a job prototype you can then share with others to see a query results report. --- ## Delete Job Deletes a job. --- ## Delete Query Set Deletes a query set. --- ## Edit Shared Job Update a shared job. --- ## Get Export Job Results To Csv Exports job results as csv file. --- ## Get Job Returns a job. --- ## Get Job Results Returns job results. --- ## Get Jobs Returns jobs. --- ## Get Presigned Download Url Returns a presigned URL to download job results as a CSV file. Use for large job results. --- ## Get Query Set Returns a query set. --- ## Get Query Sets Returns query sets. --- ## Get Shared Job Get a shared job. --- ## Get Shared Jobs Get a list of shared jobs. --- ## Import Query Set Imports a query set into deepset Cloud. --- ## Jobs deepset Cloud jobs API Security Scheme Type: http HTTP Authorization Scheme: bearer --- ## Revoke Shared Job Revoke a shared job. --- ## Start Job Starts a job. "}],"title":"Headers","type":"object"},"url":{"description":"The URL that receives the callback. deepset will send a POST request to this URL when the job finishes. The request will contain the following JSON Body: {'job_id': , 'status': }'.","examples":["https://example.com"],"title":"URL","type":"string"}},"required":["url"],"title":"JobCallback","type":"object"},"title":"Callbacks","type":"array"}},"title":"StartJobBody","type":"object"}}}}} > --- ## Update Job Updates a job. --- ## Activate Pipeline Activates the pipeline. --- ## Add Exposed Pipeline Expose a pipeline as an MCP tool. The pipeline must exist in the same workspace. Optionally provide a custom tool name and description that will be shown to MCP clients. --- ## Add Files Adds files to a dataset by calling the file service's add_file method for each file. --- ## Add OpenSearch credentials Add credentials to your own OpenSearch cluster. --- ## Add Role Adds a role to the specified organization. --- ## Add S3 Credentials Add credentials to your own S3 bucket. --- ## Apply Pipeline Migrations Apply detected migrations to a pipeline asynchronously. Creates a migration job and dispatches it to a background worker. Poll the migrations endpoint to track progress. --- ## Assign Role Assign Role --- ## Assign Search History Labels Assigns one or more labels to a search history record. Existing labels are preserved. --- ## Bulk Assign Search History Labels Assigns one or more labels to multiple search history records at once. --- ## Bulk Unassign Search History Labels Removes one or more labels from multiple search history records at once. --- ## Chat Run a chat query. Chat pipelines are based on the `chat` template that uses a search session to include search history in the chat. You can then specify how many search history items (query and answer) from a given search session you want to display in the chat. You'll need a search session ID to run the query. Use the search session endpoints to list or create search sessions. ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"params":{"anyOf":[{"additionalProperties":true,"type":"object"},{"type":"null"}],"description":"Parameters you can use to customize the pipeline. For details, see [Haystack documentation for the pipeline `run()` method](https://docs.haystack.deepset.ai/reference/pipeline-api). These filters can be used to pass additional parameters to the pipeline.(Haystack is the underlying technology for deepset.) ","title":"Pipeline Parameters"},"queries":{"description":"A list of queries you want to run through the pipeline.","items":{"type":"string"},"title":"Queries","type":"array"},"search_session_id":{"description":"The ID of the search session you want to use for chat.","format":"uuid","title":"Search Session ID","type":"string"},"view_prompts":{"default":false,"description":"Adds the runtime prompts of all nodes to the response. (Pipeline runs in debug mode.)","title":"View prompts","type":"boolean"}},"required":["queries","search_session_id"],"title":"ChatQuery","type":"object"}}},"required":true}} > --- ## Chat Stream Run a chat query and return the answer as stream. Chat pipelines are based on the `chat` template that uses a search session to include search history in the chat. You can then specify how many search history items (query and answer) from a given search session you want to display in the chat. You'll need a search session ID to run the query. Use the search session endpoints to list or create search sessions. Options: - The full result can be accessed as the last stream message if `include_result=True`. - Tool calls are streamed if `include_tool_calls=True`. Defaults to `rendered` where tool calls are converted to markdown text deltas. - Tool call results are streamed if `include_tool_call_result=True`. - Reasoning output is streamed if `include_reasoning=True`. Event data format where `delta`, `result`, `tool_call_delta`, `tool_call_result`, `reasoning`, `ping` and `error` are mutually exclusive: ``` { "query_id": UUID, "type": Literal["delta", "result", "error", "tool_call_delta", "tool_call_result", "reasoning", "ping"], "delta": Optional[StreamDelta], "result": Optional[DeepsetCloudQueryResponse], "error": Optional[str], "tool_call_delta": Optional[ToolCallDelta], "tool_call_result": Optional[ToolCallResult], "reasoning": Optional[ReasoningDelta], "index": Optional[int], "start": Optional[bool], "finish_reason": Optional[str], } ``` StreamDelta format: ``` { "text": str, "meta": Optional[dict[str, Any]], } ``` ToolCallDelta format: ``` { "index": int, "tool_name": Optional[str], "id": Optional[str], "arguments": Optional[str], } ``` ToolCallResult format: ``` { "result": str, "origin": { "tool_name": str, "arguments": dict[str, Any], "id": Optional[str], }, "error": bool, } ``` ReasoningDelta format: ``` { "reasoning_text": str, "extra": dict[str, Any], } ``` Example code to consume the stream in Python: ```python from httpx_sse import EventSource TOKEN = "MY_TOKEN" PIPELINE_URL = "https://api.cloud.deepset.ai/api/v1/workspaces/MY_WORKSPACE/pipelines/MY_PIPELINE" SEARCH_SESSION_ID = "MY_SEARCH_SESSION_ID" async def main(): query = { "query": "How does streaming work with deepset?", "include_result": True, "include_tool_calls": True, "include_tool_call_results": True, "search_session_id": SEARCH_SESSION_ID } headers = { "Authorization": f"Bearer {TOKEN}" } async with httpx.AsyncClient(base_url=PIPELINE_URL, headers=headers, timeout=httpx.Timeout(300.0)) as client: async with client.stream("POST", "/chat-stream", json=query) as response: # Check if the response is successful if response.status_code != 200: await response.aread() print(f"An error occured with status code: {response.status_code}") print(response.json()["errors"][0]) return event_source = EventSource(response) # Stream the response async for event in event_source.aiter_sse(): event_data = json.loads(event.data) chunk_type = event_data["type"] # Check the type of the chunk and print the data accordingly match chunk_type: # Delta chunk contains the next text chunk of the answer case "delta": delta = event_data["delta"] if event_data.get("start"): print(f"\n\nAnswer: ", flush=True, end="") token: str = delta["text"] print(token, flush=True, end="\n" if event_data.get("finish_reason") else "") # Result chunk contains the final pipeline result case "result": print("\n\nPipeline result: ") print(json.dumps(event_data["result"])) # Error chunk contains the error message case "error": print("\n\nAn error occurred while streaming:") print(event_data["error"]) case "tool_call_delta": tool_call_delta = event_data["tool_call_delta"] if tool_call_delta["tool_name"]: tool_id = tool_call_delta["id"] tool_name = tool_call_delta["tool_name"] print(f"\n\nTool call {tool_id} started {tool_name} with arguments: ") elif tool_call_delta["arguments"]: print(tool_call_delta["arguments"], flush=True, end="") case "tool_call_result": tool_call_result = event_data["tool_call_result"] tool_id = tool_call_result["origin"]["id"] tool_name = tool_call_result["origin"]["tool_name"] if tool_call_result["error"]: print(f"\n\nTool call {tool_name} with id {tool_id} failed.") else: print(f"\n\nTool call {tool_name} with id {tool_id} result:") print(tool_call_result["result"]) case "reasoning": reasoning = event_data["reasoning"] if event_data.get("start"): print(f"\n\nReasoning: ") print(f"{reasoning['reasoning_text']}", flush=True, end="") asyncio.run(main()) ``` ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"include_reasoning":{"default":false,"description":"Includes the reasoning output under key 'reasoning' when set to `true`. Defaults to `false`.\nThe reasoning output may include the intermediate steps taken by the model to arrive at the final answer. Example reasoning output:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"reasoning\", \"reasoning\": {\"reasoning_text\": \"This is the plan:\\nStep 1: Retrieve documents\\nStep 2: Process documents\\nStep 3: Generate answer\", \"extra\": {}}}\n```","title":"Include Reasoning","type":"boolean"},"include_result":{"default":false,"description":"Includes the result of the pipeline at the end of the stream under key 'result'.","title":"Include Result","type":"boolean"},"include_tool_call_results":{"default":false,"description":"Includes the tool call results under key 'tool_call_result' when set to `true`. Defaults to `false`.\nExample tool call result event:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_result\", \"tool_call_result\": {\"origin\": {\"tool_name\": \"example_tool\", \"arguments\": {\"arg1\": \"val1\"}, \"index\": 0}, \"result\": \"This is an example result.\", \"error\": false}}\n```","title":"Include Tool Call Results","type":"boolean"},"include_tool_calls":{"anyOf":[{"type":"boolean"},{"const":"rendered","type":"string"}],"default":"rendered","description":"Includes tool calls as tool call delta objects under key 'tool_call_delta' when set to `true`. When set to `rendered`, tool call events are rendered as markdown text instead. This parameter only affects the stream (not the final result) and is only effective when the pipeline makes tool calls (e.g. using the Agent component). Defaults to `rendered`.\nExample tool call delta events:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"tool_name\": \"example_tool\", \"index\": 0, \"id\": \"tool_call_01\"}}\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"arguments\": \"{\\\"arg1\\\": \", \"index\": 0}}\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"arguments\": \"\\\"val1\\\"}\", \"index\": 0}}\n```","title":"Include Tool Calls"},"params":{"anyOf":[{"additionalProperties":true,"type":"object"},{"type":"null"}],"description":"Parameters you can use to customize the pipeline. For details, see [Haystack documentation for the pipeline `run()` method](https://docs.haystack.deepset.ai/reference/pipeline-api). These filters can be used to pass additional parameters to the pipeline.(Haystack is the underlying technology for deepset.) ","title":"Pipeline Parameters"},"pipeline_version_id":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}],"description":"The pipeline version ID to use for serverless execution. Only valid when serverless is True. If not provided, the pipeline's default version is used.","title":"Pipeline Version Id"},"query":{"description":"The search query.","title":"Query","type":"string"},"search_session_id":{"description":"The ID of the search session you want to use for chat.","format":"uuid","title":"Search Session ID","type":"string"},"serverless":{"default":false,"description":"If True, run the pipeline via utilities without requiring deployment.","title":"Serverless","type":"boolean"},"store_search_history":{"default":true,"description":"If False, the query and response are not persisted to the chat history for the given search_session_id. Currently only honored in serverless mode.","title":"Store Search History","type":"boolean"},"view_prompts":{"default":false,"description":"Adds the runtime prompts of all nodes to the response. (Pipeline runs in debug mode.)","title":"View prompts","type":"boolean"}},"required":["query","search_session_id"],"title":"ChatStreamingQuery","type":"object"}}},"required":true}} > --- ## Clear Search History Note Removes the note from a search history record. --- ## Close Session Closes the session and starts the ingestion process. If the session is not closed explicitly, the session will be automatically closed after 24 hours. --- ## Connect Integration Connects a secret to a provider. --- ## Connect Workspace Integration Connects a secret to a provider for a workspace. --- ## Count Documents Counts the number of documents in the pipeline. --- ## Create Components Dynamic Input Output Returns updated input output schemas for Haystack components containing dynamic parameters. Dynamic parameters are component input output parameters, which are postulated by component init params. --- ## Create Feedback Adds user feedback to a specific response. Use this endpoint to collect and store user ratings, comments, " "or other feedback about the quality or relevance of a response. --- ## Create Index Creates a new pipeline index. --- ## Create Mcp Config Create an MCP server configuration for a workspace. This enables the workspace to expose selected pipelines as MCP tools that external clients (Claude, ChatGPT, etc.) can invoke. --- ## Create Organization Model Creates a new organization-level custom model definition. --- ## Create Pipeline Creates a pipeline YAML file. --- ## Create Prompt Template Creates a prompt template. The template is saved under custom templates in Prompt Studio. --- ## Create Prototype Creates a link to a pipeline prototype you can then share with others to try out. --- ## Create Query Pipeline Version Create Query Pipeline Version --- ## Create Search Session Creates a search session you can later use in chat as chat history. --- ## Create Secret Stores your secret in Haystack Enterprise Platform and returns the unique identifier for the secret. --- ## Create Skill Create Skill --- ## Create Support Request Reach out to our support team for help with your issue. --- ## Create Tags Creates tags for a specified pipeline. Users will be able to choose these tags when giving feedback " "on reponses generated by this pipeline. Use tags to structure and categorize user feedback. --- ## Create Token Creates the API key that you can use to connect Haystack Enterprise Platform to your application. --- ## Create Tool Create a new tool. This unified endpoint handles creation for all tool types (MCP server tools and pipeline tools). For MCP server tools, provide mcp_server data with URL, transport type, and optional secret ID. For pipeline tools, provide pipeline data with pipeline ID and optional input/output mappings. --- ## Create Upload Session Creates a session for uploading files and file metadata. The session remains active for 24 hours. You can upload up to 10 000 files in a session. ///${filename}`, where filename is . or ..meta.json for meta files.","title":"AWS Prefix","properties":{"fields":{"additionalProperties":{"type":"string"},"description":"The fields to include in the request to the presigned URL. These fields are required in the body of each request.","examples":[{"key":"7a3749f5-448a-475f-8d94-b87872a0342d/7d0a7027-5b3d-48f2-97d6-28fc138f2821/upload_sessions/5c38259b-19ee-4a99-8f38-7c3007dcaaae/","policy":"","x-amz-algorithm":"AWS4-HMAC-SHA256","x-amz-credential":"","x-amz-date":"20230419T152408Z","x-amz-security-token":"","x-amz-signature":""}],"title":"Request fields","type":"object"},"url":{"description":"The presigned URL to upload the file to. This URL was generated using the AWS ShareObjectPresignedUrl feature. To learn more, see [AWS Documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html).","title":"Presigned URL","type":"string"}},"required":["url","fields"],"type":"object"},"documentation_url":{"default":"https://docs.cloud.deepset.ai/docs/upload-files","description":"The URL to the documentation of the session.","title":"Session Documentation URL","type":"string"},"expires_at":{"description":"The time when the session expires.","format":"date-time","title":"Session Expires At","type":"string"},"session_id":{"description":"Unique identifier of a session.","format":"uuid","title":"Session ID","type":"string"}},"required":["expires_at","aws_prefixed_request_config"],"title":"UploadSession","type":"object"}}},"description":"Your session is created."},"402":{"description":"You can't upload to this workspace through upload sessions on a free plan. To use this feature, upgrade to a paid plan. You can still upload files through the UI at no cost."},"406":{"description":"You can't upload files because you've reached the maximum number of upload sessions allowed per user. Close existing sessions using the Close Session endpoint before starting a new one."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"}}} > --- ## Create Workspace Creates a workspace within an organization. --- ## Create Workspace Model Creates a new custom model definition in the workspace. --- ## Create Workspace Secret Stores your secret in Haystack Enterprise Platform and returns the unique identifier for the secret. --- ## Create Workspace Token Create Workspace Token --- ## Delete Exposed Pipeline Remove a pipeline from the MCP server (stop exposing it as a tool). --- ## Delete Feedback Deletes a feedback entry. You can't bring back a deleted feedback entry. --- ## Delete File Removes the file from the workspace. --- ## Delete Files Deletes files specified in the `names` parameter from a workspace. If `names` is empty, it deletes all files. --- ## Delete Index Deletes a pipeline index. --- ## Delete Mcp Config Delete the MCP server configuration, disabling MCP access for this workspace. --- ## Delete OpenSearch credentials Delete credentials to your own OpenSearch cluster. --- ## Delete Organization Model Deletes an organization-level custom model definition. --- ## Delete Pipeline Removes a pipeline from deepset within the specified workspace. --- ## Delete Pipeline Search History Deletes search history for a specific pipeline. Provide search_history_ids in the request body: \{"search_history_ids": ["uuid1", "uuid2", ...]\} Maximum 100 IDs allowed. If no body is provided or search_history_ids is null, deletes all search history for the pipeline. Deletion is done in the background and may take a few seconds to take effect. --- ## Delete Prompt Templates Deletes the prompt template with the given ID. --- ## Delete Role Deletes a role from the specified organization. user(s)."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"}}} > --- ## Delete S3 Credentials Delete credentials to your own S3 bucket. --- ## Delete Search History Label Removes a label from all search history records in a pipeline. --- ## Delete Search Session Delete a search session together with its search history. --- ## Delete Skill Delete Skill --- ## Delete Tags Permanently deletes tags with the given IDs. You can only delete tags that aren't connected to feedback entries. --- ## Delete Tool Delete a tool. Permanently removes a tool from the workspace. This operation cannot be undone. The tool will no longer be available for use by agents in this workspace. --- ## Delete User Deletes a user from Haystack Enterprise Platform. --- ## Delete User Search History Deletes all search history for a specific user. Callers may always delete their own search history; deleting another user's search history requires SEARCH_HISTORY:WRITE on the workspace. Deletion is done in the background and may take a few seconds to take effect. --- ## Delete Workspace Deletes a workspace and everything that is associated with it. Be careful as this action cannot be undone. --- ## Delete Workspace Model Deletes a workspace-scoped custom model definition. --- ## Delete Workspace Token Deletes a workspace-scoped API token. --- ## Deploy Index Deploys a pipeline index to deepset. --- ## Deploy Pipeline Deploys a pipeline in deepset. --- ## Detect Pipeline Migrations Detect possible migrations in a pipeline. Call this endpoint after a successful validation to check if the pipeline contains components that can be removed/migrated. --- ## Disconnect Integration Disconnects an connected integration. --- ## Disconnect Workspace Integration Disconnects a connected integration for a workspace. --- ## Edit Shared Prototype Updates the shared prototype description and file options. --- ## Export Feedback Exports feedback to a csv file. --- ## Export Search History Exports the search history to a downloadable CSV file. The file includes search queries, answers, prompts,feedback, and other metadata. If a single search entry has multiple feedback entries,each feedback entry appears in a separate row. prefix (for example, meta.model or meta.finish_reason).","in":"query","name":"columns","required":false,"schema":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"description":"List of columns to include in the CSV. If omitted, all columns are included. Supported fixed columns: query, answer, prompt, feedback_score, feedback_comment, feedback_tags, rank, file_name, file_id, query_id, result_id, created_at, duration, session_id, user_given_name, user_family_name, pipeline_name, api_key_name, filters, params, result_type, result_score, documents, context, feedback_id, feedback_bookmarked, feedback_created_at, feedback_created_by_user_id, labels. Dynamic pipeline meta fields can be included using the meta. prefix (for example, meta.model or meta.finish_reason).","title":"Columns"}},{"description":"Maximum number of search history items to export. Defaults to 10,000.","in":"query","name":"limit","required":false,"schema":{"default":100000,"description":"Maximum number of search history items to export. Defaults to 10,000.","title":"Limit","type":"integer"}},{"description":"Optional pipeline ID to filter search history","in":"query","name":"pipeline_id","required":false,"schema":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}],"description":"Optional pipeline ID to filter search history","title":"Pipeline Id"}},{"description":"The OData filter you want to use to in your query. It supports exact match and `AND` operations. For example, to filter for a metadata `category:news` and `published_date` greater than or equal to January 1 2025, here's what the URL could look like: 'url = \"https://api.cloud.deepset.ai/api/v1/workspaces/production/files?limit=10&filter=category eq 'news' and published_date ge '2025-01-01' \"'. OData filters only work with cursor-based pagination (leave the `page_number` field blank to enable it).To learn more about the OData filter syntax, see: [Querying Data](https://www.odata.org/getting-started/basic-tutorial/#queryData).Supported filter fields:`answer``api_key``client_source_path``created_at``created_by``deployment_id``duration``feedbacks``feedbacks/bookmarked``feedbacks/comment``feedbacks/result_id``feedbacks/score``labels``note``pipeline_version_id``query``query_id``request/filters``request/params``search_session_id``session_id``status``tags/tag_id``trace_id`","in":"query","name":"filter","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"The OData filter you want to use to in your query. It supports exact match and `AND` operations. For example, to filter for a metadata `category:news` and `published_date` greater than or equal to January 1 2025, here's what the URL could look like: 'url = \"https://api.cloud.deepset.ai/api/v1/workspaces/production/files?limit=10&filter=category eq 'news' and published_date ge '2025-01-01' \"'. OData filters only work with cursor-based pagination (leave the `page_number` field blank to enable it).To learn more about the OData filter syntax, see: [Querying Data](https://www.odata.org/getting-started/basic-tutorial/#queryData).Supported filter fields:`answer``api_key``client_source_path``created_at``created_by``deployment_id``duration``feedbacks``feedbacks/bookmarked``feedbacks/comment``feedbacks/result_id``feedbacks/score``labels``note``pipeline_version_id``query``query_id``request/filters``request/params``search_session_id``session_id``status``tags/tag_id``trace_id`","title":"Filter"}}]} > --- ## Generate Integrated Pipeline Yaml :::caution deprecated This endpoint has been deprecated and may be replaced or removed in future versions of the API. ::: Generate Integrated Pipeline Yaml --- ## Get All Documents Stream Returns documents created for a pipeline. Without pagination parameters, all documents are streamed. To paginate, pass `page_number` (1-indexed) together with `limit` in the request body. Paginated responses include `X-Total-Count` and `X-Has-More` response headers. ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"limit":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"description":"Limits the number of documents returned.","title":"Limit"},"page_number":{"anyOf":[{"minimum":1,"type":"integer"},{"type":"null"}],"description":"The page number to return when paginating. Requires 'limit' to be set. Pages are 1-indexed.","title":"Page Number"},"return_embedding":{"anyOf":[{"type":"boolean"},{"type":"null"}],"description":"Returns vector representations of the documents.","title":"Return Embedding"},"use_prefiltering":{"anyOf":[{"type":"boolean"},{"type":"null"}],"description":"Specifies if documents should be prefiltered in the document store instead of within the retriever. DEPRECATED: This parameter will be removed in a future version. Use efficient_filtering parameter instead.","title":"Use Prefiltering"}},"title":"FetchDocumentsParams","type":"object"}}},"required":true}} > --- ## Get Available Components Returns components available to be used in Haystack Enterprise Platform. By default, it returns the components for the deepset domain. --- ## Get Components Input Output Returns the haystack components available for the domain of the current version. This can be used to identify the input values required for each component and the output values that will be returned. By default, it returns the components for the deepset domain. If names are provided, it will return the input/output schema for the provided components. We use exact match for the component names. If no names are provided, it will return the input/output schema for all available components. --- ## Get Custom Component Get the details of a custom component with a specific ID. The details include the component version and status. You may need to use the Get Custom Components endpoint first to obtain the component's ID. --- ## Get Custom Component Logs Get custom component installation logs as plain text. --- ## Get Custom Components Get a list of custom components currently uploaded to Haystack Enterprise Platform. The list includes all the details of each component, such as its status and version. --- ## Get Document Displays the document content and its properties. --- ## Get File Retrieves the file contents. ' in the workspace. Check if the ID is correct. You can use the `list_files` endpoint to check file IDs."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"},"500":{"description":"File with the ID '{file_id}' doesn't have a type."}}} > --- ## Get File Meta Displays the metadata of a file. --- ## Get Index By Name Get a single pipeline index by ID. --- ## Get Indexed Files By Status Returns IDs of all files with a specific status and processed by a specified index. --- ## Get Indexes Get Indexes --- ## Get Integrations Returns the existing integrations. --- ## Get Mcp Config Get the MCP server configuration for a workspace. --- ## Get Migration By Id Return a specific migration job by its ID. --- ## Get Organization Returns the name of the current deepset organization. --- ## Get Organization Custom Models Returns organization-level custom model definitions. Supports OData ``$filter`` on ``name`` and ``provider``. --- ## Get Paginated Feedback Retrieves a paginated list of user feedback. Use this endpoint to fetch batches of feedback entries, sorted and filtered according to your preference. --- ## Get Paginated Tags Retrieves a paginated list of tags. Use this endpoint to fetch batches of feedback entries, " "sorted and filtered according to your preference. --- ## Get Permissions Returns the permissions that exist in the organization. --- ## Get Pipeline Returns a pipeline. --- ## Get Pipeline Feedback Stats Return feedback stats for a pipeline. --- ## Get Pipeline Index Logs Fetches pipeline index logs as JSON or CSV. . Check if the index name is correct and if the index exists."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"},"504":{"description":"The pipeline index logs could not be retrieved within the timeout period. Try again in a couple of minutes."}}} > --- ## Get Pipeline Index Metadata Types Returns the metadata keys and their types for a pipeline's connected index. For multi-index pipelines, the first found index's metadata is returned. --- ## Get Pipeline Issues Fetches pipeline runtime issues from pipeline logs. --- ## Get Pipeline Logs Fetches pipeline logs as JSON or CSV. --- ## Get Pipeline Metadata Field Values Returns metadata field values for a specified key across all files of a pipeline's connected index. Specify the metadata field key and the pipeline and workspace names to retrieve the corresponding values for each file. For multi-index pipelines, the first found index's metadata is searched. --- ## Get Pipeline Min Max Aggregation Metadata Returns the minimum and maximum values of a metadata field for the connected index of a given pipeline. --- ## Get Pipeline Stats Returns pipeline statistics. --- ## Get Pipeline Template Return pipeline template by pipeline_name. --- ## Get Pipeline Visualization Get Pipeline Visualization --- ## Get Pipeline Visualization(Main) Get Pipeline Visualization --- ## Get Pipeline Yaml Configs Displays the pipeline YAML configurations. --- ## Get Prompt Returns the prompt of the pipeline. --- ## Get Prompts Returns the prompts of the pipeline as a dictionary of prompt node names and their respective prompts. --- ## Get Query Pipeline Version Get Query Pipeline Version --- ## Get Query Pipeline Version Visualization Get Query Pipeline Version Visualization --- ## Get Roles Returns the roles that exist in the specified organization. --- ## Get Search History Labels Returns all unique labels used across a pipeline's search history records. --- ## Get Search Sessions Returns all search sessions. Search sessions are used in chat as chat history. --- ## Get Secret Returns the secret with the given id. --- ## Get Secrets Returns the existing secrets. --- ## Get Session Files Displays the file details of a session. Use this endpoint to check the status of the files in a session or the session expiration date. --- ## Get Session Status Displays the details of a session. Use this endpoint to check the status of the files in a session or the session expiration date. --- ## Get Shared Prototype Returns the shared pipeline prototype by ID. --- ## Get Skill Get Skill --- ## Get Temporary File Retrieves the file contents of temporary files. :param session: The database session. :param file_id: The ID of the file to retrieve. :param workspace: The workspace from which to retrieve the file. ' in the workspace. Check if the ID is correct. You can use the `list_files` endpoint to check file IDs."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"},"500":{"description":"File with the ID '{file_id}' doesn't have a type."}}} > --- ## Get Tokens Returns all API keys present in Haystack Enterprise Platform together with their properties. --- ## Get Tool Get a specific tool by ID. Retrieves detailed information about a specific tool, including its type-specific configuration (MCP server details or pipeline configuration). --- ## Get Tools Get all tools in a workspace. Returns a paginated list of tools (both MCP server tools and pipeline tools) available in the specified workspace. Tools are used in agent contexts to provide additional capabilities. --- ## Get Upload Sessions Returns a list of all active upload sessions. --- ## Get User Retrieve the properties of the specified user. --- ## Get Users Retrieve the properties of all user objects in your organization. --- ## Get Workspace By Name Returns the specified workspace and its properties. --- ## Get Workspace Custom Models Returns workspace-scoped custom model definitions. Supports OData ``$filter`` on ``name`` and ``provider``. --- ## Get Workspace Integrations Returns the existing integrations for a workspace. --- ## Get Workspace Models Returns the available models for a workspace. Custom models (workspace- and org-scoped) are listed first, followed by predefined models from the integration gateway. --- ## Get Workspace Secret Returns the secret with the given id. --- ## Get Workspace Secrets Returns the existing secrets. --- ## Get Workspace Stats Displays the number of files and documents in a workspace, the number of search requests, and the average response time. --- ## Get Workspace Token Returns the API key with the specified ID that is exclusively scoped to the workspace. --- ## Get Workspace Tokens Returns all API keys that are exclusively scoped to the specified workspace. --- ## Haystack Enterprise Platform deepset API description Security Scheme Type: http HTTP Authorization Scheme: bearer --- ## Health Checks if the API and database connection work correctly. It is enough to use the Depends, since we configured the database with `pre_ping`. Therefore the creation of the session will fail if the DB is not available. --- ## Import Custom Components Imports a custom component as a zip file. Use the [Custom component template](https://github.com/deepset-ai/dc-custom-component-template) to write your component, and then upload the zipped template. --- ## Invite User To Organization Sends an email to the user inviting them to your deepset organization. --- ## Invite User To Workspace Invites a user directly to a specific workspace with the specified role. This endpoint allows workspace administrators to invite users directly to their workspace, bypassing the organization-level invitation process. The user will be: 1. Created in the Haystack Enterprise Platform if they don't already exist 2. Added to the organization if they're not already a member 3. Assigned the specified role within the target workspace **Required Permissions:** WORKSPACE_MEMBERS write permission on the target workspace. **Valid preset roles are:** ADMIN, EDITOR --- ## List all query pipeline versions in a workspace. Lists query pipeline versions across all pipelines in the selected workspace. Supports OData filtering, pagination, and sorting. Allowed filter fields: is_draft and pipeline/name. Alias supported: pipeline_name maps to pipeline/name. Default sorting is version_number DESC. Pagination supports limit, before, after, and page_number. before/after cannot be used together, and before/after cannot be combined with page_number. Examples: GET /workspaces/default/pipeline/versions, GET /workspaces/default/pipeline/versions?filter=is_draft%20eq%20true, GET /workspaces/default/pipeline/versions?filter=pipeline/name%20eq%20'my-pipeline', GET /workspaces/default/pipeline/versions?filter=pipeline_name%20eq%20'my-pipeline', GET /workspaces/default/pipeline/versions?field=version_number&order=DESC&limit=20&page_number=1. --- ## List OpenSearch credentials List all OpenSearch credentials that exist for the current organization. --- ## List Available S3 Credentials List all S3 bucket credentials that exist for the current organization. --- ## List Datasets Lists all datasets in a workspace with their associated files. Supports pagination. --- ## List Exposed Pipelines List pipelines currently exposed as MCP tools in this workspace. --- ## List Files Lists files in a workspace. This endpoint supports pagination and filtering by name and metadata. --- ## List Migrations Return all migration jobs for a pipeline, optionally filtered by status. --- ## List Pipeline Templates Retrieves the list of the pipeline templates. --- ## List Pipelines Lists all the pipelines in the workspace. --- ## List Prompt Templates Retrieves the list of prompt templates for the given workspace. --- ## List Prototypes Lists active shared prototypes. --- ## List Public Prompt Templates Lists public prompt templates available in Prompt Studio. --- ## List Query Pipeline Versions List Query Pipeline Versions --- ## List Skills List Skills --- ## List Workspaces Lists all deepset workspaces and their properties. --- ## Parse Tools Parse a tool definition from a pipeline (e.g. Agent). This endpoint takes a tool definition as provided in a pipeline context (such as when initializing an Agent with tools) and parses it into the format used by the validate and create tool endpoints. This allows users to verify and create tools based on definitions they are already using in their pipelines. --- ## Patch Query Pipeline Version Patch Query Pipeline Version --- ## Patch Token Updates the name of a token in the database. --- ## Pipeline Search History Returns the search history for a pipeline, which includes information such as the query, the answer, the pipeline used, and more. Supports pagination, filtering, and sorting. --- ## Pipeline Search History Archive Retrieves pipeline's complete search history sorted by the most recent items first. Pipeline's search history is only available 30 minutes after completing a search request. To retrieve recent search history, use the [Pipeline Search History](https://docs.cloud.deepset.ai/reference/pipeline_search_history_api_v1_workspaces__workspace_name__pipelines__pipeline_name__search_history_get) endpoint. --- ## Pipeline Search History Result Returns the search history for a specific query_id. --- ## Query Documents Searches the documents for the specified query. ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"query":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"The search query.","title":"Query"},"query_emb":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"description":"The vector representation of the query.","title":"Query Emb"},"return_embedding":{"anyOf":[{"type":"boolean"},{"type":"null"}],"description":"Returns vector representations of the documents.","title":"Return Embedding"},"top_k":{"default":10,"description":"The number of results to return.","title":"Top K","type":"integer"},"use_prefiltering":{"anyOf":[{"type":"boolean"},{"type":"null"}],"deprecated":true,"description":"Specifies if documents should be prefiltered in the document store instead of within the retriever. DEPRECATED: This parameter will be removed in a future version. Use efficient_filtering parameter instead.","title":"Use Prefiltering"}},"title":"QueryDocumentsParams","type":"object"}}},"required":true}} > --- ## Query Files Executes an SQL query on the workspace's file index and returns the raw response. The query must follow the [OpenSearch SQL Query syntax](https://docs.opensearch.org/latest/search-plugins/sql/sql/index/).The table must be `file`. --- ## Read Users Me Retrieve the properties of the current user. --- ## Read Users Me Workspace Permissions Returns the permissions for the current user on the specified workspace. It is a list of Permission objects, where each Permission has: - "asset" is the type of the asset the user has permissions to. - "action" is the action the user can perform on the asset. Example: ``` for an admin: [{"asset": "pipelines", "action": "write"}] for a search_user: [{"asset": "pipelines", "action": "read"}, ...] ``` --- ## Remove Role Remove Role --- ## Remove Secret Deletes a secret from Haystack Enterprise Platform. --- ## Remove Token Deletes the API key with the ID you specify. --- ## Remove Workspace Secret Deletes a secret from Haystack Enterprise Platform. --- ## Restore Pipeline Version Restore Pipeline Version --- ## Retrieve Token Returns the API key with the ID you specify. This ID can be obtained by calling the list endpoint of this resource. --- ## Revoke Shared Prototype Revokes a shared pipeline prototype. Once you revoke a prototype, users can no longer access it. --- ## Run Component Runs a haystack component with the provided parameters. This is useful for testing components or running them with specific input data. --- ## Run Component Workspace Runs a haystack component with the provided parameters in workspace scope (e.g. using workspace secrets). This is useful for testing components or running them with specific input data. --- ## Run Pipeline Runs a haystack pipeline with the provided configuration and inputs. This is useful for testing pipelines or running them with specific input data. --- ## Run Pipeline Workspace Runs a haystack pipeline with the provided configuration and inputs in workspace scope. This is useful for testing pipelines or running them with specific input data. --- ## Schedule Single File For Indexing Reindexes a single file on a pipeline index. --- ## Search Run a search query using a deployed pipeline. Use this endpoint for generative, extractive, and document search pipelines. For chat pipelines, use the Chat endpoint. ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"params":{"anyOf":[{"additionalProperties":true,"type":"object"},{"type":"null"}],"description":"Parameters you can use to customize the pipeline. For details, see [Haystack documentation for the pipeline `run()` method](https://docs.haystack.deepset.ai/reference/pipeline-api). These filters can be used to pass additional parameters to the pipeline.(Haystack is the underlying technology for deepset.) ","title":"Pipeline Parameters"},"queries":{"description":"A list of queries you want to run through the pipeline.","items":{"type":"string"},"title":"Queries","type":"array"},"search_session_id":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}],"description":"The ID of the search session you want to use for chat.","title":"Search Session ID"},"view_prompts":{"default":false,"description":"Adds the runtime prompts of all nodes to the response. (Pipeline runs in debug mode.)","title":"View prompts","type":"boolean"}},"required":["queries"],"title":"PipelineQuery","type":"object"}}},"required":true}} > --- ## Search Count Returns the number of search requests per time bucket. Supports daily or hourly granularity, optional pipeline filtering, and configurable time range. --- ## Search Files Executes an OpenSearch query on the workspace's file index and returns the raw response. The query must follow the [OpenSearch Query DSL syntax](https://opensearch.org/docs/latest/query-dsl/). --- ## Search History Returns the search history for a workspace. The history includes information such as the query, the answer, the pipeline used, and more. Supports two pagination methods: - **Offset-based**: Use `offset` (integer) and `limit` parameters - **Cursor-based**: Use `cursor` (opaque string from previous response) with `limit` When `cursor` is provided, it takes precedence over `offset`. You can filter the results using OData syntax via the `filter` query parameter. Supported fields include: - `created_at`: Filter by timestamp (e.g., `filter=created_at ge 2025-11-21T00:00:00Z`) - `query`: Filter by search query text - `answer`: Filter by answer text - `api_key`: Filter by API key - `created_by`: Filter by user ID - `session_id` or `search_session_id`: Filter by session ID - `deployment_id`: Filter by deployment ID (e.g., `filter=deployment_id eq ''`) - `tags/tag_id`: Filter by feedback tag ID - `feedbacks/score`: Filter by feedback score - `feedbacks/comment`: Filter by feedback comment - `feedbacks/bookmarked`: Filter by bookmark status (e.g., `filter=feedbacks/bookmarked eq true`) - `feedbacks`: Filter by feedback existence (e.g., `filter=feedbacks ne null` for entries with feedback) Example date range filter: `?filter=created_at ge 2025-11-01T00:00:00Z and created_at le 2025-11-30T23:59:59Z` Example bookmark filter: `?filter=feedbacks/bookmarked eq true` --- ## Search Stream Run a search using a pipeline and return the answer as stream. Options: - The full result can be accessed as the last stream message if `include_result=True`. - Tool calls are streamed if `include_tool_calls=True`. Defaults to `rendered` where tool calls are converted to markdown text deltas. - Tool call results are streamed if `include_tool_call_result=True`. - Reasoning output is streamed if `include_reasoning=True`. Event data format where `delta`, `result`, `tool_call_delta`, `tool_call_result`, `reasoning`, `ping` and `error` are mutually exclusive: ``` { "query_id": UUID, "type": Literal["delta", "result", "error", "tool_call_delta", "tool_call_result", "reasoning", "ping"], "delta": Optional[StreamDelta], "result": Optional[DeepsetCloudQueryResponse], "error": Optional[str], "tool_call_delta": Optional[ToolCallDelta], "tool_call_result": Optional[ToolCallResult], "reasoning": Optional[ReasoningDelta], "index": Optional[int], "start": Optional[bool], "finish_reason": Optional[str], } ``` StreamDelta format: ``` { "text": str, "meta": Optional[dict[str, Any]], } ``` ToolCallDelta format: ``` { "index": int, "tool_name": Optional[str], "id": Optional[str], "arguments": Optional[str], } ``` ToolCallResult format: ``` { "result": str, "origin": { "tool_name": str, "arguments": dict[str, Any], "id": Optional[str], }, "error": bool, } ``` ReasoningDelta format: ``` { "reasoning_text": str, "extra": dict[str, Any], } ``` Example code to consume the stream in Python: ```python from httpx_sse import EventSource TOKEN = "MY_TOKEN" PIPELINE_URL = "https://api.cloud.deepset.ai/api/v1/workspaces/MY_WORKSPACE/pipelines/MY_PIPELINE" async def main(): query = { "query": "How does streaming work with deepset?", "include_result": True, "include_tool_calls": True, "include_tool_call_results": True, } headers = { "Authorization": f"Bearer {TOKEN}" } async with httpx.AsyncClient(base_url=PIPELINE_URL, headers=headers, timeout=httpx.Timeout(300.0)) as client: async with client.stream("POST", "/search-stream", json=query) as response: # Check if the response is successful if response.status_code != 200: await response.aread() print(f"An error occured with status code: {response.status_code}") print(response.json()["errors"][0]) return event_source = EventSource(response) # Stream the response async for event in event_source.aiter_sse(): event_data = json.loads(event.data) chunk_type = event_data["type"] # Check the type of the chunk and print the data accordingly match chunk_type: # Delta chunk contains the next text chunk of the answer case "delta": delta = event_data["delta"] if event_data.get("start"): print(f"\n\nAnswer: ", flush=True, end="") token: str = delta["text"] print(token, flush=True, end="\n" if event_data.get("finish_reason") else "") # Result chunk contains the final pipeline result case "result": print("\n\nPipeline result: ") print(json.dumps(event_data["result"])) # Error chunk contains the error message case "error": print("\n\nAn error occurred while streaming:") print(event_data["error"]) case "tool_call_delta": tool_call_delta = event_data["tool_call_delta"] if tool_call_delta["tool_name"]: tool_id = tool_call_delta["id"] tool_name = tool_call_delta["tool_name"] print(f"\n\nTool call {tool_id} started {tool_name} with arguments: ") elif tool_call_delta["arguments"]: print(tool_call_delta["arguments"], flush=True, end="") case "tool_call_result": tool_call_result = event_data["tool_call_result"] tool_id = tool_call_result["origin"]["id"] tool_name = tool_call_result["origin"]["tool_name"] if tool_call_result["error"]: print(f"\n\nTool call {tool_name} with id {tool_id} failed.") else: print(f"\n\nTool call {tool_name} with id {tool_id} result:") print(tool_call_result["result"]) case "reasoning": reasoning = event_data["reasoning"] if event_data.get("start"): print(f"\n\nReasoning: ") print(f"{reasoning['reasoning_text']}", flush=True, end="") asyncio.run(main()) ``` ",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},"circular(LogicalCondition)"]},"title":"Conditions","type":"array"},"operator":{"description":"The operator you want to use for logical conditions.","title":"Logical Condition Operator","enum":["AND","OR","NOT"],"type":"string"}},"required":["operator","conditions"],"title":"LogicalCondition","type":"object"},{"properties":{"field":{"description":"The field you want to compare.","title":"Comparison Condition Field","type":"string"},"operator":{"description":"The operator you want to use for comparison.","title":"Comparison Condition Operator","enum":["==","!=",">",">=","<","<=","in","not in"],"type":"string"},"value":{"description":"The value you want to compare the field to.","title":"Comparison Condition Value"}},"required":["field","operator","value"],"title":"ComparisonCondition","type":"object"},{"additionalProperties":false,"properties":{},"title":"EmptyFilters","type":"object"},{"type":"null"}],"description":"Filters you can use to narrow down the search. For more information, see [filtering logic](https://docs.cloud.deepset.ai/docs/filtering-logic).","title":"Haystack Filters"},"include_reasoning":{"default":false,"description":"Includes the reasoning output under key 'reasoning' when set to `true`. Defaults to `false`.\nThe reasoning output may include the intermediate steps taken by the model to arrive at the final answer. Example reasoning output:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"reasoning\", \"reasoning\": {\"reasoning_text\": \"This is the plan:\\nStep 1: Retrieve documents\\nStep 2: Process documents\\nStep 3: Generate answer\", \"extra\": {}}}\n```","title":"Include Reasoning","type":"boolean"},"include_result":{"default":false,"description":"Includes the result of the pipeline at the end of the stream under key 'result'.","title":"Include Result","type":"boolean"},"include_tool_call_results":{"default":false,"description":"Includes the tool call results under key 'tool_call_result' when set to `true`. Defaults to `false`.\nExample tool call result event:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_result\", \"tool_call_result\": {\"origin\": {\"tool_name\": \"example_tool\", \"arguments\": {\"arg1\": \"val1\"}, \"index\": 0}, \"result\": \"This is an example result.\", \"error\": false}}\n```","title":"Include Tool Call Results","type":"boolean"},"include_tool_calls":{"anyOf":[{"type":"boolean"},{"const":"rendered","type":"string"}],"default":"rendered","description":"Includes tool calls as tool call delta objects under key 'tool_call_delta' when set to `true`. When set to `rendered`, tool call events are rendered as markdown text instead. This parameter only affects the stream (not the final result) and is only effective when the pipeline makes tool calls (e.g. using the Agent component). Defaults to `rendered`.\nExample tool call delta events:\n```json\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"tool_name\": \"example_tool\", \"index\": 0, \"id\": \"tool_call_01\"}}\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"arguments\": \"{\\\"arg1\\\": \", \"index\": 0}}\n{\"query_id\": \"e2084408-48f8-4f52-9b59-43dd924705ef\", \"type\": \"tool_call_delta\", \"tool_call_delta\": {\"arguments\": \"\\\"val1\\\"}\", \"index\": 0}}\n```","title":"Include Tool Calls"},"params":{"anyOf":[{"additionalProperties":true,"type":"object"},{"type":"null"}],"description":"Parameters you can use to customize the pipeline. For details, see [Haystack documentation for the pipeline `run()` method](https://docs.haystack.deepset.ai/reference/pipeline-api). These filters can be used to pass additional parameters to the pipeline.(Haystack is the underlying technology for deepset.) ","title":"Pipeline Parameters"},"query":{"description":"The search query.","title":"Query","type":"string"},"search_session_id":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}],"description":"The ID of the search session you want to use for chat.","title":"Search Session ID"},"view_prompts":{"default":false,"description":"Adds the runtime prompts of all nodes to the response. (Pipeline runs in debug mode.)","title":"View prompts","type":"boolean"}},"required":["query"],"title":"StreamingQuery","type":"object"}}},"required":true}} > --- ## Set Default Pipeline Sets a pipeline as the default pipeline for search. --- ## Set Search History Note Sets or replaces the note on a search history record. --- ## Start Debug Tunnel Start a debug tunnel for a pipeline. If another debug tunnel is already running for this pipeline, the existing tunnel will be stopped and a new one will be started. --- ## Stream Pipeline Workspace Streams a haystack pipeline execution with Server-Sent Events (SSE) format in workspace scope. This endpoint executes a Haystack pipeline and streams the results as they become available. The response uses Server-Sent Events (SSE) format with the following event types: - **delta**: Content chunks from streaming-capable components (e.g., LLM generators) - **tool_call_delta**: Structured tool call events (if `include_tool_calls` is `true`) - **tool_call_result**: Tool call results (if include_tool_call_results is True) - **reasoning**: Reasoning steps emitted by the pipeline (if include_reasoning is True) - **result**: Final pipeline result (if include_result is True) - **error**: Error messages if pipeline execution fails When `include_tool_calls` is set to `rendered`, tool calls are emitted as markdown text in `delta` events. --- ## Unassign Search History Labels Removes one or more labels from a search history record. --- ## Undeploy Index Disables a pipeline index in deepset. --- ## Undeploy Pipeline Undeploys a pipeline in deepset. Undeployed pipelines cannot be used for search. --- ## Update Exposed Pipeline Update the MCP tool metadata (name, description, instructions) for an exposed pipeline. --- ## Update Feedback Modifies and existing feedback entry. Use this endpoint to update the content and rating of a specific piece of user feedback. --- ## Update File Meta Updates the metadata of a file and of the documents created from this file. You can modify existing metadata or add new ones. If you send a new metadata dictionary, it's merged with the existing dictionary. To change the value of an existing key, pass this key with the new value. To add a new key:value pair, simply pass it in the request. It will add the new metadata and keep the existing ones. To delete a key:value pair, pass the key with `None` as value, for example: "author":"None". (But to fully delete all metadata, upload the file again.) --- ## Update File Meta Bulk Updates the metadata of the files and of the documents created from these files. You can modify existing metadata or add new ones. If you send a new metadata dictionary, it's merged with the existing dictionary. To change the value of an existing key, pass this key with the new value. To add a new key:value pair, simply pass it in the request. It will add the new metadata and keep the existing ones. To delete a key:value pair, pass the key with `None` as value, for example: "author":"None". (But to fully delete all metadata, upload the file again.) --- ## Update Index Updates specific fields of a pipeline index. Only description can be updated while the index is deployed. To update name or config_yaml, the index must be undeployed. --- ## Update Integration Updates an already connected integration. --- ## Update Mcp Config Update the MCP server configuration for a workspace. --- ## Update Organization Model Updates an existing organization-level custom model definition. --- ## Update Pipeline Updates the pipeline name, service level (development or production), or status. Search users have permission to change pipeline status only. --- ## Update Pipeline Visualization Update Pipeline Visualization --- ## Update Pipeline Visualization(Main) Update Pipeline Visualization --- ## Update Pipeline Yaml :::caution deprecated This endpoint has been deprecated and may be replaced or removed in future versions of the API. ::: **Deprecated.** Updates the pipeline YAML file. This endpoint is deprecated and will be removed in a future release. To update a pipeline, use the pipeline versions API instead: fetch the latest version, create a new version if the latest is not a draft, then patch it via `PATCH /workspaces/{workspace_name}/pipelines/{pipeline_name}/versions/{version_id}`. --- ## Update Prompt Template Updates the prompt template with the given ID. --- ## Update Role Adds a role to the specified organization. --- ## Update Secret Updates your secret in Haystack Enterprise Platform. --- ## Update Skill Update Skill --- ## Update Tool Update an existing tool. Allows partial updates to a tool's properties. Only the fields provided in the request will be updated; other fields will remain unchanged. The tool type cannot be changed after creation. --- ## Update User Organization Role Update user permissions. --- ## Update User Settings Update user settings. Only the user themselves can update their own settings. --- ## Update Workspace Integration Updates an already connected integration for a workspace. --- ## Update Workspace Model Updates an existing workspace-scoped custom model definition. --- ## Update Workspace Secret Updates your secret in Haystack Enterprise Platform. --- ## Update Workspace Token Updates the name, role, and personal flag of a workspace-scoped API token. --- ## Upload File Uploads a file into the workspace. You can also use this endpoint to create a text file. To do that, enter the file name and text as its contents. ' already exists in the workspace."},"413":{"description":"Too large payload.Either the file uploaded is larger than 200 MB or the metadata you tried to upload is too large. The string '' of key '' is longer than 32766 bytes, which approximately equals the same number of characters.To upload files larger than 200 MB, use the [deepset SDK](https://github.com/deepset-ai/deepset-cloud-sdk)."},"415":{"description":"Haystack Enterprise Platform supports .txt, .csv, .json, .xml, .html, .md, .pdf, .docx, .pptx, .xlsx, .xlsb, .xlsm, .msg, .zip and ..DS_Store files. Upload a file in the supported format."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"}}} > --- ## Upload Temporary File Uploads a file into the workspace. You can also use this endpoint to create a text file. To do that, enter the file name and text as its contents. ' of key '' is longer than 32766 bytes, which approximately equals the same number of characters.To upload files larger than 200 MB, use the [deepset SDK](https://github.com/deepset-ai/deepset-cloud-sdk)."},"415":{"description":"Haystack Enterprise Platform supports .txt, .csv, .json, .xml, .html, .md, .pdf, .docx, .pptx, .xlsx, .xlsb, .xlsm, .msg, .zip and ..DS_Store files. Upload a file in the supported format."},"422":{"content":{"application/json":{"schema":{"properties":{"detail":{"items":{"properties":{"ctx":{"title":"Context","type":"object"},"input":{"title":"Input"},"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"}}},"description":"Validation Error"}}} > --- ## Validate Organization Generation Kwargs Validates model parameters schema: checks that it is a valid JSON schema. --- ## Validate Organization Model Validates the chat_generator_config for an organization-level custom model. --- ## Validate Pipeline Validates a pipeline YAML. Use this endpoint to validate your pipeline configuration before saving it. --- ## Validate Tool Validate a new tool configuration without saving it. This unified endpoint handles validation for all tool types (MCP server tools and pipeline tools). For MCP server tools, provide mcp_server data with URL, transport type, and optional secret ID. For pipeline tools, provide pipeline data with pipeline ID and optional input/output mappings. If a new secret is provided for MCP server authentication, this endpoint creates and saves the secret. --- ## Validate Workspace Model Validates the chat_generator_config for a workspace-scoped custom model. --- ## Workspace Remove Role Workspace Remove Role --- ## Deploy with Hayhooks # Deploy Pipelines with Hayhooks Use Hayhooks to deploy your pipelines and agents. A pipeline must be deployed so that you can run searches with it. *** ## About This Task To deploy a pipeline or agent created in self-hosted Builder, you must use Hayhooks. Hayhooks is 's software for serving and deploying Haystack pipelines and agents. To learn more, see [Hayhooks documentation](https://deepset-ai.github.io/hayhooks/). ## Prerequisites - A pipeline or agent created in Builder. ## Deploy Your Pipeline ### Export Your Pipeline as YAML In Builder, click the Export icon, choose **YAML**, and click **Download**. {/* TODO: Add screenshot - export_pipeline.png is missing */} This downloads the pipeline as `pipeline.yaml` to your computer. ### Deploy Your Pipeline with Hayhooks 1. Log in to Hayhooks and click **Deploy** in the navigation. 2. Click **Create Deployment**. 3. Give your deployment a name and click **Create**. --- ## Jobs(Concepts) Jobs are workflows that run on the data from your workspace using a pipeline you chose. After configuring and creating a job, you can run it immediately or save it as a draft for later. *** Currently, supports the batch question answering job that you can use to process queries in bulk. You can run the query set once on all your files or repeat the queries per each file. A job processes 10 queries at once. Once you have the results, you can easily share them with anyone you wish without creating an account or logging in. Just generate a link to an HTML page that you can share. On the Jobs page, you can view all the jobs created in your workspace. Clicking a job opens its details page, where you can check: - The job ID - The pipeline it uses — click the pipeline name to go directly to the pipeline details page - The query set - The number of queries run - Results ## Query Batch To run a batch question answering job, you must create a CSV file with your queries that you then upload to when creating a job. The CSV query set contains the queries and any labels or groupings you want to use for your queries on the shareable HTML page. For example, when running a job on property reports, for a query "What is the address of the building?" you may want the label to be "Address". You may also want to group queries like "What is the address of the building" and "How many floors does this building have" under a group name "Property Details". You can add filters to the query set to narrow down the set of files the job runs on. Filters are simply file metadata. For example, your files can have a metadata key called "type" with values "property report", "news", "reviews," and so on. You may then set a filter `{"field": "type", "operator": "==", "value": "property report"}` to run the job on property reports only. Filters also make it possible to run the same query against multiple files. Simply repeat the query in your query set specifying the file name in the _filters_ column. For examples of query sets and how they impact the results page, see [Prepare a Query Set](/docs/how-to-guides/working-with-jobs/prepare-a-query-set.mdx). You can also change runtime parameters for components in your pipeline. Pass the new parameter values in the query set's params column. Use this format: `{ "component_name": { "parameter1_name": "parameter1_value" }, "component2_name": { "parameter1_name": "parameter1_value", "parameter2_name": "parameter2_value" }}`. The parameters from query set override the parameters set in pipeline configuration. For more examples, see [Prepare a Query Set](/docs/how-to-guides/working-with-jobs/prepare-a-query-set.mdx). For more information on filters, see [Filter Syntax](/docs/how-to-guides/working-with-your-data/working-with-metadata/filtering-logic.mdx). --- ## Pipelines Pipelines are powerful and highly flexible systems that form the engine for your app. They consist of components that process your data and perform various tasks on it. Each component in a pipeline passes its output to the next component. *** # How Do Pipelines Work? Pipelines are composed of connected components. Each component processes a piece of your data, such as documents, and performs specific tasks before passing the output to the next component. For example, a basic RAG pipeline may include: - A `TextEmbedder` that takes the user query and turns it into a vector. - A `Retriever` that receives the vector from the `TextEmbedder` and uses it to fetch relevant documents from the document store. - An `LLM` that injects the user query and the documents from the `Retriever` into the prompt and generates the response. Components function like modular building blocks that you can mix, match, and replace to form various pipeline configurations, such as loops, branches, or simultaneous flows. When connecting the components, it's crucial to ensure the output type of one component matches the input type of the next. Each component receives only the data it needs, which speeds up the pipeline and makes it easier to debug. ## Connection Types Pipelines in are flexible and multifunctional. While you can still create simple pipelines performing one function, like answering queries, you can also use them to build complex workflows. ### Smart Connections Components connect when their input and output types are compatible. In most cases, the types must match. However, pipelines also support smart connections for certain type combinations: - `List` types: You can connect multiple lists of the same type to a component that accepts a list as input. For example, you can connect multiple `Converters` that produce lists of documents to a `DocumentWriter` that accepts a list of documents as input. The pipeline combines the lists into a single list and passes it to the component. - `String` to `ChatMessage`: A `string` automatically converts to a `ChatMessage` with the *user* role. This is useful when you pass plain text to a `ChatPromptBuilder` or `ChatGenerator`. - `ChatMessage` to `string` or a `list of strings` or a `list of ChatMessage`: This conversion makes it possible to connect a `ChatGenerator` to inputs such as the query parameter of a `Retriever`. - `List of string` to a `string` or `ChatMessage`: Pipelines support connections between list of strings and components that accept a single `string` or `ChatMessage`. For example, an `OpenAIGenerator`'s `replies` can connect to `OpenSearchHybridRetriever`'s `query`. - `List of ChatMessage` to a single `ChatMessage` or `string`: The pipeline supports connections between lists of ChatMessages and components that accept a single `ChatMessage` or `string`. For example, `OpenAIChatGenerator`'s `messages` can connect to `OpenSearchHybridRetriever`'s `query`. This table summarizes connections between input and output types enabled by smart connections: | Sender Output Type | Receiver Input Type | What happens | |-------------|---------------|------------------| | List of Documents (multiple senders to same input) | List of Documents | Lists are merged into one. | | List of ChatMessage (multiple senders to same input) | List of ChatMessage | Lists are merged into one. | | List of strings (multiple senders to same input) | List of strings | Lists are merged into one. | | string | ChatMessage | Converted to a `ChatMessage` with the *user* role. | | ChatMessage | string | Content is extracted as a string. | | List of ChatMessage | string or ChatMessage | First message is used (for example, as a query). | | List of string | string or ChatMessage | First string is used. | This table shows component-level connections for both list merging and type conversions: | Sender | Receiver | What Happens | |-----------------|-------------------|------------------| | BM25 Retriever, Embedding Retriever output: `documents` | Rankers (for example, `TransformersSimilarityRanker`) input: `documents` | List merge | | Ranker or multiple retrievers output: `documents` | `PromptBuilder`, `AnswerBuilder` input: `documents` (if configured in the template) | List merge | | Ranker or multiple retrievers output: `documents` | `ChatPromptBuilder` input: `documents` | List merge | | Multiple converters output: `documents` | `DocumentSplitter` input: `documents` | List merge | | Multiple converters or `DocumentSplitter` output: `documents` | `DocumentWriter` input: `documents` | List merge | | Multiple converters or `DocumentSplitter` output: `documents` | Document Embedders (for example `SentenceTransformersDocumentEmbedder`) input: `documents` | List merge | | `ChatPromptBuilder` output: `prompt` [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx) output: `messages` | `Agent` input: `messages` | List merge | | Generator, ChatGenerator output: `replies` | Retriever, Ranker, `AnswerBuilder` input: `query` `PromptBuilder` input: `question`| List of ChatMessages converted to string | | `ChatGenerator` output: `replies` | `AnswerBuilder` input: `replies` | Type conversion| | `Agent` output: `last_message` | `SentenceTransformersTextEmbedder` input: `text` Retriever input: `query` | Type conversion | Smart connections make many "glue" components like `DocumentJoiner`, `ListJoiner`, and `OutputAdapter` unnecessary. To learn how to update your existing pipelines, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ### Connection Validation When you connect components in a pipeline, it validates that their outputs and inputs match and, if needed, produces detailed errors. In Builder, these validation errors appear in the Issues panel at the bottom of the canvas. Click **Inspect** next to an issue to jump directly to the incompatible connection or misconfigured component. Click **Fix with AI** to open the AI assistant, which reasons through the fix and can apply it for you. You can manage all your connections in the Connections panel at the bottom of the canvas. ### Branches Pipelines can branch to process data simultaneously. For example, each pipeline branch can have a different converter, each dedicated to a specific file type, allowing for efficient parallel processing. ### Loops In loops, components operate iteratively, with a set limit on repetitions. This is useful in scenarios such as self-correcting loops, where a validator component checks the generator's output and potentially cycles it back for correction until it meets the quality standard and can be sent further down the pipeline. # How Do Pipelines Use Your Files? Pipelines run on the documents produced by the indexes they're connected to. An index preprocesses the files from a workspace, converts them into documents, and writes them into a document store where a pipeline can access them. A single pipeline can be connected to multiple indexes. For details, see [Indexes](../indexes/indexes.mdx). One file may produce multiple documents. Documents inherit metadata from files. Your indexing pipeline defines the exact steps for preprocessing the files. ## Building Pipelines Pipelines contain recipes for how to execute a query. Pipelines can perform different tasks, such as querying, summarizing, or arriving at an answer after a series of steps involving tool calling. This is an example of a RAG pipeline that runs on your files in , receives the user query, retrieves the relevant documents, and processes them through the components to arrive at an answer:
Example of a pipeline ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: Standard-Index-English-EU-Demo-Schengen max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id llm: type: haystack.components.generators.chat.llm.LLM init_parameters: # You can swap this for any other model. Switch to the Builder view and choose another model from the list on the component card. chat_generator: type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator init_parameters: model: "gpt-5.4" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {% for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor %} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" system_prompt: "" attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: llm.documents inputs: query: - retriever.query - ranker.query - llm.question filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources outputs: documents: attachments_joiner.documents messages: llm.messages max_runs_per_component: 100 metadata: {} ```
### Inputs Pipelines always take `Input` as the first component. When working in Builder, click **Add** to open the component library and drag `Input` onto the canvas and then connect it to the components that should receive its outputs. When working in YAML editor, you must explicitly specify the inputs and the components that receive them: ```yaml inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" ``` Filters are documents' metadata keys by default. This means that if your documents have the following metadata: `{"category": "news"}`, when searching in Playground, users can narrow down the search to the documents matching this category. You can also pass filters at search time with the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) endpoint. For more information about filters, see [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx). ### Outputs The output of pipelines matches the output of the last component. However, it must be one of the following data classes: - List of `Document` objects (usually document search pipelines) - List of `Answer` objects, including the following subclasses: - List of `ExtractedAnswer` objects (usually extractive question answering pipelines) - List of `GeneratedAnswer` objects (pipelines that use Generator components) - List of `ChatMessage` objects (usually pipelines that use large language models to generate answers) The output can be a list of documents, a list of answers, a list of chat messages, or all of them. Ensure the last component in your pipeline produces at least one of these outputs. In Builder, to finalize the pipeline with the correct output, drag the `Output` component onto the canvas and connect it to the components that produce the outputs you want to include. When working in the YAML editor, you must explicitly specify the outputs and the components that provide them: ```yaml outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents messages: "llm.messages" # The output of the pipeline is the generated answers ``` ## Pipeline Service Levels To save costs and meet your infrastructure and service requirements, your pipelines are assigned service levels. There are three service levels available: - **Draft**: This is a service level automatically assigned to new and undeployed pipelines, so that you can easily distinguish them from the deployed ones. - **Development**: Pipelines at this level are designed for testing and running experiments. They have no replicas by default, and their time to standby is short, so they can save resources whenever these pipelines aren't used. When you deploy a draft pipeline, it becomes a development pipeline. - **Production**: This level is recommended for business-critical scenarios where you need the pipeline to be scalable and reliable. Pipelines at this level include one replica by default and a longer time-to-standby period than other service levels. With heavy traffic, the number of replicas grows up to 10. This table gives an overview of the default settings that come with each service level: | Service level | Description | Idle Timeout | Scaling (replicas) | How to enable | |---------------|-----------------------------------------------------------------------------|------------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | Production | Designed for critical business scenarios that require reliable and scalable pipelines. | 24 hours | 1 at all times, scales up to 10 if traffic is heavy | - In , on the Pipelines page - Through the `Update Pipeline` REST API endpoint | | Development | Designed for testing and experimenting purposes. | 20 minutes | 0 | - By switching off the Production service level for a deployed production pipeline in - Through the `Update Pipeline` REST API endpoint - By deploying a draft pipeline | | Draft | Indicates an undeployed pipeline. | n/a | 0 | - By undeploying a production or development pipeline - All new pipelines are automatically classified as drafts | _Idle timeout_ is the time after which an unused pipeline enters a standby mode to save resources. Inactive pipelines don't use up the pipeline hours included in your plan. You can customize the idle timeout for each pipeline in the pipeline's **Settings** tab or through the `Update Pipeline` REST API endpoint. The maximum idle timeout is 30 days. To use a pipeline on standby, activate it either on the Pipelines page or by initiating a search using that pipeline. _Replicas_ are the number of duplicate versions of a pipeline that are available. In case there is a spike in demand, seamlessly switches to a functioning replica to maintain uninterrupted service. You can configure the minimum and maximum number of replicas in the pipeline's **Settings** tab or through the `Update Pipeline` REST API endpoint. The maximum number of replicas is 10. You can change the service level of your pipeline at any time. For details, see [Change the Pipeline's Service Level](/docs/how-to-guides/designing-your-pipeline/changing-the-pipelines-service-level.mdx). ## Managing Pipelines All the pipelines created in a workspace are listed on the Pipelines page, where you can view and manage them. Click a pipeline to open it and navigate to the different sections. ### Build When you click a pipeline name, you land in Builder. You can use Builder to build and test your pipeline. For details, see [Creating a pipeline](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). ### Playground This is where you can test your pipeline. You can type a query and see the results. You can also upload files and test your pipeline with them. For details, see [Testing your pipeline](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). ### Analytics Analytics is where you can check all the information about your pipeline, including pipeline logs and search history. You can check the following information about the pipeline: - Pipeline overview, including query volume, feedback distribution, and response times. - Search history - Logs #### Overview The overview shows the a KPI dashboard with key performance metrics in an easy-to-read format: - **Total queries**: Total number of queries your pipeline processed. This metric helps you understand usage patterns and traffic volume. - **Documents**: Total number of documents indexed for this pipeline. - **Feedback coverage**: Percentage of queries that received user feedback. Higher feedback coverage gives you better insights into pipeline performance. If this shows "N/A", it means no feedback was given yet. - **Average response time**: Average time it took to generate a response. Monitor this metric to identify performance issues or improvements after configuration changes. - **Minimum inference time**: The fastest response time recorded across all queries. This helps you understand your pipeline's best case performance. - **Maximum inference time**: The slowest response time recorded across all queries. Use this metric to identify potential performance bottlenecks or outliers. - **Query volume**: Number of queries your pipeline processed over the last 7 days. - **Feedback distribution**: Distribution of feedback received for the pipeline's responses. - **Query Activity Heatmap**: Shows when your pipeline is most active by displaying query volume across hours and days. This helps you understand usage patterns, identify peak activity period, or plan maintenance windows. From the overview section, you can click **Playground** to quickly test the pipeline. #### Search History The Search History tab shows the queries run with this pipeline and their results, including all the details. You can customize the Search History table columns to show the information you need. You can also export the entire search history as a CSV file for a specific time period. This is useful for analyzing the performance of your pipeline over time. You can also use AI-powered Feedback Insights to analyze feedback patterns and generate executive summaries to help you understand performance trends and identify areas for improvement. Expand the Feedback Insights panel to see the insights. You can start with one of the suggested prompts or enter your own query. Based on the prompt, AI analyzes your pipeline activity and generates a summary. To inspect a specific query, click **More Actions > Details** in the query row. This opens a detailed view of the query, including the query text, the answer, the feedback, the timestamp, and the metadata. You can also see the conversation history for the query. You can group queries by hashtags and add notes to individual queries to help you keep track of important information. Both notes and hashtags are searchable. You can view and manage them if you enable the Notes and Hashtags columns in the Search History table. To do this: 1. On the Pipeline Details page, click **Search History**. 2. Click **Manage table preferences**. 3. Choose to display the *Note* and *Hashtags* columns. You can then add notes and hashtags to your queries using these columns in the table. #### Logs Use the logs to troubleshoot issues with your pipeline. You can filter the logs by message and pipeline type or date added. You can also search for keywords in log messages. ### Settings The Settings tab is where you can check your pipeline ID and configure its settings, such as MCP tools, GPU acceleration, pipeline scaling, and idle timeout. #### MCP Tool Use this section to expose your pipeline as an MCP tool to AI coding assistants like Cursor, Claude Code, and GitHub Copilot. For details, see [Use Your Pipelines as MCP Tools](/docs/how-to-guides/productionizing-your-pipeline/expose-pipeline-as-mcp-tool.mdx). #### GPU Settings Pipelines use CPU by default. Turn on GPU support on the Settings tab when your pipeline includes components that run better on a GPU, such as embedders, generators, or custom components that use AI models. When GPU support is on, the pipeline checks whether a component needs a GPU and assigns one automatically. GPUs are only used when required and are not reserved for the entire pipeline run. If GPU support is off and your pipeline includes components that rely on a GPU, those components run on the CPU instead. This can slow down processing and may cause timeouts, especially for larger or more complex pipelines. For detailed instructions, see [Enable GPU Acceleration](/docs/how-to-guides/designing-your-pipeline/set-additional-params/enable-gpu.mdx). #### Pipeline Scaling To increase availability, set the number of replicas allocated to a pipeline. automatically scales replicas up or down based on traffic, and depending on the maximum and minimum number of replicas you set. For production pipelines, set at least two replicas. This setup helps keep your pipeline available if one replica fails. Adding more replicas can increase your costs. #### Idle Timeout Set the idle timeout to define how long a pipeline can remain inactive before it enters standby mode. When a pipeline becomes idle, scales its replicas down to zero. Idle pipelines do not consume the pipeline hours included in your plan. For example, if you set the idle timeout to 12 hours, the pipeline enters standby mode after 12 hours of inactivity. This setting is useful for saving costs when you don't need your pipeline to be always available. #### Feedback Tags Add tags that users can select when giving feedback on the pipeline's responses. This helps you group feedback and analyze it. For details, see [Collect Feedback](/docs/how-to-guides/evaluating-your-pipeline/collect-feedback.mdx). --- ## Common Component Combinations Let's look at examples of components that often go together to understand how they work. ## PromptBuilder and Generator Generators are components designed to interact with large language models (LLMs). Any LLM app requires a Generator component specific to the model provider used. Generator needs a prompt as input, which is created using `PromptBuilder`. With `PromptBuilder`, you can define your prompt as a Jinja2 template. `PromptBuilder` processes the template, fills in the variables, and sends it to the Generator. To connect these components, link the `prompt` output of `PromptBuilder` to the `prompt` input of the `Generator`, as shown below: Example YAML configuration: ```yaml components: qa_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: qa_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0.0 seed: 0 connections: - sender: qa_prompt_builder.prompt receiver: qa_llm.prompt ``` ## ChatPromptBuilder and ChatGenerator ChatGenerators are a type of Generators designed to work with chat LLMs in conversational scenarios. They receive the rendered prompt from a `ChatPromptBuilder`. The prompt for ChatGenerators is a list of `ChatMessage` objects, which means it follows a strict format: ```yaml ChatMessage format - _content: # this is the beginning of the first ChatMessage - content_type: content # this is the message content, it can be text, tool call or a tool call result. You can add variables to the content, just like in PromptBuilder. _role: role # this specifies who sends this content, available roles are: system, tool, user, assistant ``` This is an example of a prompt with two `ChatMessages`, one for the `system` and one for the `user` role. The message for the system contains instructions for the LLM, while the message for the users contains user's query. It's also used to pass the retrieved documents to the LLM: ```yaml Example template for ChatPromptBuilder - _content: - text: | You are a helpful assistant answering the user's questions based on the provided documents. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Provided documents: {% for document in documents %} Document [{{ loop.index }}] : {{ document.content }} {% endfor %} Question: {{ query }} _role: user ``` You pass the prompt in the `template` parameter of a `ChatPromptBuilder` and then connect the `prompt` output to the `messages` input of a ChatGenerator: ## Generator and DeepsetAnswerBuilder The Generator’s output is `replies`, a list of strings containing all the answers the LLM generates. However, pipelines require outputs in the form of `Answer` objects or its subclasses, such as `GeneratedAnswer`. Since the pipeline’s output is the same as the output of its last component, you need a component that converts `replies` into the `GeneratedAnswer` format. This is why Generators are always paired with a `DeepsetAnswerBuilder`. `DeepsetAnswerBuilder` processes the Generator’s replies and transforms them into a list of `GeneratedAnswer` objects. It can also include documents in the answers, providing references to support the generated responses. This feature is particularly useful when you need answers that are backed by reliable sources. To connect these two components, you simply link Generator’s `replies` output with `DeepsetAnswerBuilder`’s `replies` input. Additionally, `DeepsetAnswerBuilder` requires the query as an input to include it in the `GeneratedAnswer`. Ensure the query is properly connected to the `DeepsetAnswerBuilder` through the `Input` component to complete the configuration. `DeepsetAnswerBuilder` also accepts the prompt as input. If it receives the prompt, it adds it to the `GeneratedAnswer`'s metadata. This is useful if you need a prompt as part of the API response from . Here’s how to connect the components: :::tip `DeepsetAnswerBuilder` is available in the _Augmenters_ group in the components library. ::: ## ChatGenerators and AnswerBuilders :::tip Simplify this pattern With [smart connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections), the pipeline now converts between `ChatMessage` and `String` automatically. You can skip the `OutputAdapter` in most cases. For details, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ::: ChatGenerators can't connect directly to `DeepsetAnswerBuilder` as their input and output types don't match. You can use `OutputAdapter` in between to convert the ChatGenerator's output (list of `ChatMessage` objects) into a list of strings that `DeepsetAnswerBuilder` accepts: ```yaml OutputAdapter's configuration OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: typing.List[str] custom_filters: unsafe: false ``` This how you build the connections in Pipeline Builder: Another option is to simply use `AnswerBuilder` after a ChatGenerator. Their inputs and outputs are compatible. :::info AnswerBuilder and DeepsetAnswerBuilder The main difference between `AnswerBuilder` and `DeepsetAnswerBuilder` is that the latter is better at handling complicated references and can extract content from XML tags. ::: ## Embedders Embedders are a group of components that turn text or documents into vectors (embeddings) using models trained to do that. Embedders are specific to the model provider, with at least two embedders available for each: - Document Embedder - Text Embedder Document Embedders are used in indexing pipelines to embed documents before they’re written into the document store. In most cases, this means a `DocumentEmbedder` is connected to the `DocumentWriter`: The connection is simple - you link `DocumentEmbedder`’s `documents` output with `DocumentWriter`’s `documents` input. Text Embedders are used in query pipelines to embed the query text and pass it on to the next component, typically a Retriever. The `Input` component’s `text` output is connected to the `TextEmbedder`’s `text` input. The `TextEmbedder` then generates embeddings, and its `embedding` output is linked to the `query_embedding` input of the Retriever. Keep in mind that the `DocumentEmbedder` in your indexing pipeline and the `TextEmbedder` in your query pipeline must use the same model. This ensures the embeddings are compatible for accurate retrieval. --- ## Custom Components Custom components let you execute your own Python code in your pipelines and share it with your organization. *** ## Why Custom Components? While we offer multiple pre-built components to handle various tasks, you might need something more tailored to your needs. With custom components, you can add your own code that: - Adjusts the functionality to your specific needs and use cases. - Integrates proprietary algorithms or business logic. - Extends the pipeline's capabilities. - Is shareable across pipelines in your workspace or organization. uses the open source Haystack framework as the underlying technology. Custom components are based on Haystack's [components](https://docs.haystack.deepset.ai/docs/components). To learn more about Haystack, visit [the Haystack website](https://haystack.deepset.ai/). To learn about custom components in Haystack, see [Creating Custom Components](https://docs.haystack.deepset.ai/docs/custom-components). ## Ways to Create Custom Components There are two ways to create custom components in : - **With the `Code` component** (recommended): Write your component code directly in Builder, test it, and save it as a custom component to share with your workspace or organization. This is the recommended approach for most use cases. - **With a GitHub template**: Fork our GitHub template, write your component in your IDE, and upload it to . Best for components that need external pip dependencies, full version control, or CI/CD testing. This table summarizes the key differences: | Feature | `Code` Component | GitHub Template | |---------|-----------------|-----------------| | Sharing | Workspace-scoped or organization-wide when saved | Organization-wide | | Reusability | Saved components appear in the **Your Custom Components** section in Component Library | Available in the **Your Custom Components** section in Component Library | | Creation method | Write and save directly in Builder | Fork a GitHub template, write code in your IDE, and upload | | Init parameters | Supported | Supported | | External dependencies | Not supported beyond what's already available in | Supported | | Code versioning | No | Yes, via GitHub | | Code testing | Run the component in Builder to test it | Add automated testing via GitHub Actions | | Updates | Edit inline in a pipeline, or in Settings if saved; each pipeline keeps its own copy | Upload a new version | For detailed instructions, see [Add Custom Code](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/add-custom-code.mdx). ## Creating Custom Components with the `Code` Component The `Code` component is the recommended way to create custom components in . You write and test the component directly in Builder, then optionally save it to share or reuse. You can also use the AI Assistant to generate the code for you. ### How It Works When you save a `Code` component as a custom component: - The component is stored in and scoped to your workspace or the whole organization. - It appears in the **Your Custom Components** section in the Component Library in Builder. - When you or a teammate drags the component into a pipeline, the code is copied into that pipeline. Each pipeline gets its own independent copy, so updating the saved component later doesn't affect pipelines already using it. - You can view and delete saved components from the **Settings** page at the organization or workspace level. ### Workflow 1. In Builder, find the `Code` component and drag it onto the canvas. 2. Write your component code or use the AI Assistant to generate the code for you. 3. Test the component by clicking **Run** on the component card. 4. Click **Save as Custom Component** to save and share the component. 5. To use it in another pipeline, open that pipeline in Builder, find the component in the Component Library, and drag it onto the canvas. ### Permissions You need the following permissions to save a component as a custom component: - Organization Admin: required to share a component with the entire organization. - Workspace write permission: required to share a component within a workspace. For step-by-step instructions, see [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx). ## Creating Custom Components with a GitHub Template If you need external pip dependencies, full GitHub-based versioning, or CI/CD testing, you can create custom components using our GitHub template. ### Custom Components Template ### Workflow Here's the whole workflow, step-by-step: 1. Fork the [GitHub](https://github.com/deepset-ai/dc-custom-component-template) template we provide. 2. Use the template to create your custom components. 3. When your components are ready, import them to . You can do this by creating a release of your repository or zipping the template package and uploading it to using the API or the commands. The package is validated on upload to check if its structure complies with the template. 4. Check the upload status: 1. If you uploaded through a repository release, check the Actions tab. If all the checks have passed, your component is uploaded. 2. If you uploaded using API or commands, use the [Get Custom Component](/docs/api/main/get-custom-component-api-v-2-custom-components-custom-component-id-get.api.mdx) endpoint. If the component is uploaded successfully, you can use it in your pipelines. 3. Or simply edit a pipeline where you want to use your custom component and check if your component is already in the component library. 5. Use the component in your pipelines just like any other component. Components support dependencies and have access to the internet. To update custom components, upload a new version. ### Template Structure We offer a template for creating custom components you can access at [GitHub](https://github.com/deepset-ai/dc-custom-component-template). There are two files in the repo that you'll need to modify: - `./dc-custom-component-template/src/dc_custom_component/example_components//.py`: This is where your component code is stored. The base path `./dc-custom-component-template/src/dc_custom_component/` must remain unchanged, but you can create additional subfolders to organize your custom components within the `dc_custom_component` folder. You can create a separate folder for each component, with its own `.py` file, or group multiple components in a single folder and manage them through one `.py` file. Whatever works best for you. The folder name appears as the group's name in the components library in Pipeline Builder, where you can find your custom component. For example, if you place your custom component under `./dc-custom-component-template/src/dc_custom_component/components/rankers/custom_ranker.py`, it will show up in Pipeline Builder in the Rankers group. - `./dc-custom-component-template/src/dc_custom_component/__about__.py`: This is the component version. Make sure to update it here every time you upload a new version. The version is set for all components in the package. - `./dc-custom-component-template/pyproject.toml`: If your component has any dependencies, you can add them in this file in the `dependencies` section. ### Versioning Here's how pipelines use your custom component versions: - New pipelines can only use the latest version of your components. - Running pipelines use the component version that was the latest at the time when then were deployed. To use a new version of a custom component, undeploy the pipelines using the component and deploy them again. To compare different versions of a component, upload a package with both versions included in the `.py` file, similar to how you would upload two components at once. Ensure each version has a unique name. After that, create multiple pipelines, each using a different component version, and compare their performance. ### Handling Non-JSON Serializable Types If your component uses an input type that's not JSON-serializable, you must implement its serialization methods: `to_dict()` and `from_dict()`. These methods define how to convert the type into a dictionary, which is needed for storage or transmission. One example is the `Secret` type. This type enhances security by preventing you from directly passing sensitive information, like API keys, into initialization parameters. Since it's not a JSON-serializable type, you must implement the `to_dict()` and `from_dict()` methods to convert it into a JSON-serializable string for proper handling. For an example of a component that uses the `Secret` type, see the Examples section below. ### Using Components In a Pipeline Once your component is in , you can add it to your pipelines using Pipeline Builder. Create or edit your pipeline as you normally would and add your custom component to it by dragging it from the Your Custom Components section in the Component Library. Optionally, you can: - Add the initialization parameters your component requires in the `__init__()` method. For example, this custom component is initialized with the `pydantic_model` parameter: ```python from pydantic import ValidationError from typing import Optional, List from colorama import Fore from haystack import component # Define the component input parameters @component class OutputValidator: """ Validates if a JSON object complies with the provided Pydantic model. If it doesn't, this component returns an error message along with the incorrect object. """ def __init__(self, pydantic_model: pydantic.BaseModel): """ Initialize the OutputValidator component. :param pydantic_model: The Pydantic model the JSON object should comply with. """ self.pydantic_model = pydantic_model self.iteration_counter = 0 # Define the component output @component.output_types(valid_replies=List[str], invalid_replies=Optional[List[str]], error_message=Optional[str]) def run(self, replies: List[str]): """ Validate a JSON object. :param replies: The LLM output that should be validated. """ self.iteration_counter += 1 ## Try to parse the LLM's reply ## # If the LLM's reply is a valid object, return `"valid_replies"` try: output_dict = json.loads(replies[0]) self.pydantic_model.parse_obj(output_dict) print( Fore.GREEN + f"OutputValidator at Iteration {self.iteration_counter}: Valid JSON from LLM - No need for looping: {replies[0]}" ) return {"valid_replies": replies} # If the LLM's reply is corrupted or not valid, return "invalid_replies" and the "error_message" for LLM to try again except (ValueError, ValidationError) as e: print( Fore.RED + f"OutputValidator at Iteration {self.iteration_counter}: Invalid JSON from LLM - Let's try again.\n" f"Output from LLM:\n {replies[0]} \n" f"Error from OutputValidator: {e}" ) return {"invalid_replies": replies, "error_message": str(e)} ``` - Add docstrings. This is not required, but we recommend adding docstrings to explain the purpose and functionality of your component. These docstrings appear as component tooltips in Pipeline Builder and also serve as component documentation. To add a docstring, place it under the component name within triple quotes (`"""`). You can use Markdown formatting: ```python @component class ComponentName: # Add docstrings here like that: """ Description of the component. You can use Markdown formatting. """ # If your component takes parameters, add their explanations like this: def method_name(self, param1_name: Optional[type] = default_value, param2_name: Required[type] = default_value2): """ Description of what the method does :param param1_name: Description of the parameter. You can use Markdown formatting. :param param2_name: Description of the parameter. You can use Markdown formatting. """ ``` - Add other methods your component needs. ## Examples ### Components With No Parameters This is an example of a very basic component called WelcomeTextGenerator with just the `run()` method. The component takes `name` as an input parameter and returns a welcome text with the `name`, converted to upper case, and a note. ```python @component # decorator class WelcomeTextGenerator: # component name """ A component generating personal welcome message and making it upper case. Example from [Haystack documentation](https://docs.haystack.deepset.ai/docs/custom-components#extended-example). """ @component.output_types(welcome_text=str, note=str) # types of data the component outputs def run(self, name: str) -> Dict[str, str]: # parameters for the run() method, the types match the output_types (two strings) """ Generate a welcome message and make it upper case. :param name: The name of the user to include in the message. """ return { "welcome_text": ( "Hello {name}, welcome to Haystack!".format(name=name) ).upper(), "note": "welcome message is ready", } # For `name: Jane` the component will return: # {'welcome_text': "HELLO JANE, WELCOME TO HAYSTACK!", 'note':"welcome message is ready"} ``` ### Components With Initialization Parameters Here's an example of a component with initialization parameters. The component is called `OutputValidator` and is designed to validate if the JSON object an LLM generated complies with the provided Pydantic model. It's initialized with a `pydantic_model`. At runtime, it expects `replies`, which is the LLM's output to verify. It then returns the valid objects and invalid objects. If there are invalid objects, it also returns an error message: ```python from pydantic import ValidationError from typing import Optional, List from colorama import Fore from haystack import component # Define the component input parameters @component class OutputValidator: """ Validates if a JSON object complies with the provided Pydantic model. If it doesn't, this component returns an error message along with the incorrect object. """ def __init__(self, pydantic_model: pydantic.BaseModel): """ Initialize the OutputValidator component. :param pydantic_model: The Pydantic model the JSON object should comply with. """ self.pydantic_model = pydantic_model self.iteration_counter = 0 # Define the component output @component.output_types(valid_replies=List[str], invalid_replies=Optional[List[str]], error_message=Optional[str]) def run(self, replies: List[str]): """ Validate a JSON object. :param replies: The LLM output that should be validated. """ self.iteration_counter += 1 ## Try to parse the LLM's reply ## # If the LLM's reply is a valid object, return `"valid_replies"` try: output_dict = json.loads(replies[0]) self.pydantic_model.parse_obj(output_dict) print( Fore.GREEN + f"OutputValidator at Iteration {self.iteration_counter}: Valid JSON from LLM - No need for looping: {replies[0]}" ) return {"valid_replies": replies} # If the LLM's reply is corrupted or not valid, return "invalid_replies" and the "error_message" for LLM to try again except (ValueError, ValidationError) as e: print( Fore.RED + f"OutputValidator at Iteration {self.iteration_counter}: Invalid JSON from LLM - Let's try again.\n" f"Output from LLM:\n {replies[0]} \n" f"Error from OutputValidator: {e}" ) return {"invalid_replies": replies, "error_message": str(e)} ``` For more information and examples, see Haystack resources: - Examples of custom components in Haystack: [Custom Components](https://haystack.deepset.ai/integrations?type=Custom+Component). - [Generating Structured Output with Loop-Based Auto-Correction](https://haystack.deepset.ai/tutorials/28_structured_output_with_loop): An example that uses a custom component to validate JSON objects generated by an LLM. ### Components Connecting to a Third-Party Provider You can add components to integrate tools and services into . An example are the `VoyageTextEmbedder` and `VoyageDocumentEmbedder`, which are components developed by a Haystack community member to connect to Voyage AI. Using custom components, you can connect to any provider. Components that connect to third-party providers need an API key of the provider to connect to it. An example may be a generator connecting to a model provider. The easiest way to handle this is by storing the API key in an environment variable and then retrieving it in the component's `run()` method. You can also use the Secrets feature to manage your API keys in custom components. This requires adding serialization and deserialization method to your component's code. For examples and explanation, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ### Components With Non-JSON Serializable Input Types Let's look at an example of a component using the `Secret` type. It has the necessary import statement, then the `warm_up()` method to load the API key before pipeline validation, and finally the serialization `to_dict()` and deserialization `from_dict()` methods: ```python from haystack import component, default_from_dict, default_to_dict from haystack.utils import Secret, deserialize_secrets_inplace from typing import Any, Dict @component class MyComponent: def __init__(self, model_name: str, api_key: Secret = Secret.from_env_var("ENV_VAR_NAME")): self.model_name = model_name self.api_key = api_key self.backend = None def warm_up(self): # Call api_key.resolve_value() to load the API key from the environment variable # We put the resolution in warm_up() to avoid loading the API key during pipeline validation if self.backend is None: self.backend = SomeBackend(self.model_name, self.api_key.resolve_value()) def to_dict(self) -> Dict[str, Any]: # Make sure to include any other init parameters in the to_dict method return default_to_dict( self, model_name=self.model_name, api_key=self.api_key.to_dict(), ) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MyComponent": # Make sure to use deserialize_secrets_inplace to load the Secret object init_params = data.get("init_parameters", {}) deserialize_secrets_inplace(init_params, keys=["api_key"]) return default_from_dict(cls, data) def run(self, my_input: Any): if self.backend is None: raise RuntimeError("The component wasn't warmed up. Run 'warm_up()' before calling 'run()'.") return self.backend.process(my_input) ``` For more information about how secrets work in Haystack, see [Secret Management](https://docs.haystack.deepset.ai/docs/secret-management). For details on secrets in , see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). ### Components Using Haystack Experimental Features You can use custom components to add components from the [haystack-experimental](https://github.com/deepset-ai/haystack-experimental) package to your pipelines and try them out. Bear in mind that the experimental components are not suitable for production pipelines as they're likely to change or get deprecated. For more information about haystack-experimental, see [Haystack documentation](https://github.com/deepset-ai/haystack-experimental) and [ and Haystack](/docs/getting-started/whats-deepset-cloud/deepset-cloud-and-haystack.mdx). To add an experimental component, import it and then inherit from it in you custom component code. This example adds `LLMMetadataExtractor` from the haystack-experimental package: ```python from haystack import component from haystack_experimental.components.extractors.llm_metadata_extractor import ( LLMMetadataExtractor, ) @component class ExperimentalLLMMetadataExtractor(LLMMetadataExtractor): """Haystack Experimental LLM Metadata Extractor""" ``` Save the component code, upload it to , and use it like you would any other custom component. ### Components In a Pipeline This is an example of an indexing pipeline that uses a custom component called `CharacterSplitter`. This component splits text into smaller chunks by the number of characters you specify. It takes the `split_length` parameter, accepts a list of documents as input, and returns as list of split documents. ```yaml components: # ... custom_component: # this is a custom name for your component, it's up to you init_parameters: #here you can set init parameters for your component, if you added any. Otherwise delete init_parameters. split_length: 50 type: dc_custom_component.components.splitters.character_splitter.CharacterSplitter # this is the path to your custom component; it reflects the template structure starting from the "src" directory and separated with periods. # If you changed the path, the type must reflect this. # This component's path was "./dc-component-template/src/dc_custom_component/components/splitters/character_splitter.py" pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/e5-base-v2" connections: - receiver: custom_component.documents # Define how to connect to your component to other components, make sure the input and output types match. sender: pptx_converter.documents - receiver: document.embedder.documents sender: custom_component.documents inputs: # Define the inputs for your pipeline files: # These components will receive files as input # ... max_loops_allowed: 100 metadata: {} ``` --- ## Multimodal Systems Multimodal systems can process, understand, and generate information across multiple types such as text, images, audio, and video. Learn what's possible in . *** ## Overview You can build systems that combine multiple data types and formats. These can range from simple setups (such as transcribing speech to text or generating image captions) to more advanced ones that process and analyze videos. Such systems have a variety of applications. They can give your AI assistants new capabilities but also help people with disabilities. ## Types of Multimodal Systems Below are common types of multimodal systems you can build with using existing components. ### Audio-Based Systems With , you can build speech to text systems that take audio input and return textual answers. The steps to building such systems include: 1. Uploading audio files to a workspace. 2. Preprocessing audio files with a transcriber component, like `RemoteWhisperTranscriber`, that converts the audio into text documents. 3. Writing the resulting documents into a document store so that your query pipeline can retrieve them. 4. Build a query pipeline that answers questions based on those transcribed documents. #### Example This is an example index that transcribes audio files using `RemoteWhisperTranscriber` and writes the transcribed documents into a document store: ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - audio/wav splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE RemoteWhisperTranscriber: type: haystack.components.audio.whisper_remote.RemoteWhisperTranscriber init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: whisper-1 api_base_url: organization: http_client_kwargs: connections: # Defines how the components are connected - sender: document_embedder.documents receiver: writer.documents - sender: file_classifier.audio/wav receiver: RemoteWhisperTranscriber.sources - sender: splitter.documents receiver: document_embedder.documents - sender: RemoteWhisperTranscriber.documents receiver: splitter.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ### Image-Based Systems You can easily create systems that process, analyze, or generate images. Some examples include: - Visual question answering (ask questions about image content, including scanned documents) - Image generation (create images from textual descriptions) - Image analysis or classification (compare, classify, or interpret images) - Working in images often requires specialized models, like DALL-E, for generating images. is model-agnostic so you can easily try out different models To work with images, you may need a special index. offers two index templates designed specifically for visual search that you can use out-of-the-box: - *Image-to-Text*: Uses the Azure's Document Intelligence OCR service to extract text from PDF files. Use this template if you want to run OCR on your PDFs. - *Visual Search*: Processes images by extracting their text descriptions. It also processes PDF files by splitting each PDF by page and checking each page for text content that can be extracted. - If the is not text content, the page is sent to a vision LLM that extracts its content. The extracted content is then send to the Embedder and indexed into the document store. - If the is text content, it's sent to the Embedder and indexed into the document store. Both templates are available for English and German. Once your data is indexed, you can build a query pipeline that prompts an LLM to operate on the images. #### Example: Visual Question Answering Here's how you could build a system to answer questions about images: 1. First, create an index using the Visual Search template. 2. Then, build a query pipeline using one of the Visual RAG Question Answering templates. This is an example index that prepares files for visual search. It uses a vision LLM to extract the content of PDF files. The documents resulting from PDFs are then split and written into the OpenSearch document store. It doesn't split images. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - application/pdf - image/jpg - image/jpeg - image/png - image/gif PDFConverter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false PageSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: page split_length: 1 split_overlap: 0 respect_sentence_boundary: false language: en use_split_rules: false extend_abbreviations: false ContentFilter: type: haystack.components.routers.document_length_router.DocumentLengthRouter init_parameters: threshold: 1 ImageSourceListJoiner: type: haystack.components.joiners.list_joiner.ListJoiner init_parameters: list_type_: List[Union[str, pathlib.Path, haystack.dataclasses.ByteStream]] ImageFileToDocument: type: haystack.components.converters.image.file_to_document.ImageFileToDocument init_parameters: store_full_path: true DocumentJoinerForExtraction: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate LLMDocumentContentExtractor: type: haystack.components.extractors.image.llm_document_content_extractor.LLMDocumentContentExtractor init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o timeout: 120 generation_kwargs: max_tokens: 16384 temperature: 0 prompt: | You are part of an information extraction pipeline that extracts the content of image-based documents. Extract the content from the provided image. You need to extract the content exactly. Format everything as markdown. Make sure to retain the reading order of the document. **Headers- and Footers** Remove repeating page headers or footers that disrupt the reading order. Place letter heads that appear at the side of a document at the top of the page. **Visual Elements** Do not extract figures, drawings, maps, graphs or any other visual elements. Instead, add a caption that describes briefly what you see in the visual element. You must describe each visual element. If you only see a visual element without other content, you must describe this visual element. Enclose each image caption with [img-caption][/img-caption] **Tables** Make sure to format the table in markdown. Add a short caption below the table that describes the table's content. Enclose each table caption with [table-caption][/table-caption]. The caption must be placed below the extracted table. **Forms** Reproduce checkbox selections with markdown. Go ahead and extract! Document: file_path_meta_field: file_path root_path: detail: size: raise_on_failure: true max_workers: 4 DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate Embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: BAAI/bge-m3 normalize_embeddings: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE S3Downloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: file_root_path: file_extensions: file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key connections: # Defines how the components are connected - sender: FileTypeRouter.application/pdf receiver: PDFConverter.sources - sender: PDFConverter.documents receiver: PageSplitter.documents - sender: PageSplitter.documents receiver: ContentFilter.documents - sender: ContentFilter.long_documents receiver: DocumentJoiner.documents - sender: FileTypeRouter.image/jpg receiver: ImageSourceListJoiner.values - sender: FileTypeRouter.image/jpeg receiver: ImageSourceListJoiner.values - sender: FileTypeRouter.image/png receiver: ImageSourceListJoiner.values - sender: FileTypeRouter.image/gif receiver: ImageSourceListJoiner.values - sender: DocumentJoiner.documents receiver: Embedder.documents - sender: Embedder.documents receiver: DocumentWriter.documents - sender: ImageSourceListJoiner.values receiver: ImageFileToDocument.sources - sender: ImageFileToDocument.documents receiver: DocumentJoinerForExtraction.documents - sender: ContentFilter.short_documents receiver: DocumentJoinerForExtraction.documents - sender: LLMDocumentContentExtractor.documents receiver: DocumentJoiner.documents - sender: DocumentJoinerForExtraction.documents receiver: S3Downloader.documents - sender: S3Downloader.documents receiver: LLMDocumentContentExtractor.documents inputs: # Define the inputs for your pipeline files: # These components will receive the files to index as input - FileTypeRouter.sources max_runs_per_component: 100 metadata: {} ``` This is an example of a Visual RAG QA pipeline with Claude Sonnet 3.5 that uses the files indexed with the template above to answer queries related to images. It uses both keyword and semantic retrieval to fetch matching documents. For retrieval, it uses textual versions of documents (for images, these are the image captions created during indexing). It then groups all documents resulting from one file based on their metadata using the `MetaFieldGroupingRanker`, replaces textual documents with actual images, and sends them to the LLM in the prompt. ```yaml # haystack-pipeline components: BM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 Embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: BAAI/bge-m3 EmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate Ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: BAAI/bge-reranker-v2-m3 top_k: 5 MetaFieldGroupingRanker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id sort_docs_by: split_id FileDownloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: file_extensions: - .pdf - .png - .jpeg - .jpg - .gif file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key DocumentToImageContent: type: haystack.components.converters.image.document_to_image.DocumentToImageContent init_parameters: detail: auto ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: '*' template: | {%- message role="user" -%} Answer the questions briefly and precisely using the images and text passages provided. Only use images and text passages that are related to the question to answer it. Give reasons for your answer. In your answer, only refer to images and text passages that are relevant in answering the query. Each image is related to exactly one document. You see the images in exactly the same order as the documents. Only use references in the form [NUMBER OF IMAGE] if you are using information from an image. Or [NUMBER OF DOCUMENT] if you are using information from a document. For example, for Document [1] use the reference [1]. For Image 1 use reference [1] as well. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} Relates to image: [{{ loop.index }}] {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} {%- if image_contents|length > 0 %} {%- for img in image_contents -%} {{ img | templatize_part }} {%- endfor -%} {% endif %} {%- endmessage -%} LLM: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: anthropic.claude-3-5-sonnet-20241022-v2:0 generation_kwargs: max_length: 8192 temperature: 0 Adapter: init_parameters: custom_filters: {} output_type: List[str] template: '{{ [(messages|last).text] }}' unsafe: false type: haystack.components.converters.output_adapter.OutputAdapter AnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: # Defines how the components are connected - sender: BM25Retriever.documents receiver: DocumentJoiner.documents - sender: EmbeddingRetriever.documents receiver: DocumentJoiner.documents - sender: Embedder.embedding receiver: EmbeddingRetriever.query_embedding - sender: DocumentJoiner.documents receiver: Ranker.documents - sender: Ranker.documents receiver: MetaFieldGroupingRanker.documents - sender: MetaFieldGroupingRanker.documents receiver: FileDownloader.documents - sender: FileDownloader.documents receiver: ChatPromptBuilder.documents - sender: DocumentToImageContent.image_contents receiver: ChatPromptBuilder.image_contents - sender: FileDownloader.documents receiver: AnswerBuilder.documents - sender: FileDownloader.documents receiver: DocumentToImageContent.documents - sender: ChatPromptBuilder.prompt receiver: LLM.messages - sender: LLM.replies receiver: Adapter.messages - sender: Adapter.output receiver: AnswerBuilder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "BM25Retriever.query" - "ChatPromptBuilder.question" - "AnswerBuilder.query" - Embedder.text - Ranker.query filters: # These components will receive a potential query filter as input - "BM25Retriever.filters" - "EmbeddingRetriever.filters" outputs: # Defines the output of your pipeline documents: "FileDownloader.documents" # The output of the pipeline is the retrieved documents answers: "AnswerBuilder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` #### Example: Image Generation This system generates images directly from user prompts, so it doesn't need any indexed data. It's important to use an image generation model, such as DALL-E, in the pipeline. The easiest way to build a pipeline that can generate images is by using the DallE-Image-Generator template. Deploy the pipeline and that's it. ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: '{{query}}' dalle_image_generator: type: haystack.components.generators.openai_dalle.DALLEImageGenerator init_parameters: model: dall-e-3 quality: standard size: 1024x1024 response_format: url timeout: 60 answer_formatter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: |- {% set ns = namespace(doc_string='') %} {% set ns.doc_string = ns.doc_string + '## Query:\n' + query + '\n\n' %} {% set ns.doc_string = ns.doc_string + '## OpenAIs Revised Prompt:\n' + revised_prompt + '\n\n' %} {% set ns.doc_string = ns.doc_string + '![](' + images[0] + ')' + '\n\n' %} {% set answer = [ns.doc_string] %} {{ answer }} output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: {} connections: - sender: prompt_builder.prompt receiver: dalle_image_generator.prompt - sender: dalle_image_generator.revised_prompt receiver: answer_formatter.revised_prompt - sender: dalle_image_generator.images receiver: answer_formatter.images - sender: answer_formatter.output receiver: answer_builder.replies - sender: prompt_builder.prompt receiver: answer_builder.prompt max_runs_per_component: 100 metadata: {} inputs: query: - prompt_builder.query - answer_formatter.query - answer_builder.query outputs: answers: answer_builder.answers ``` ### Combining Modalities Finally, you can build systems that mix different data types. For instance: - Audio to image: Accept audio as input, then generate images based on the audio. - Image and text: Process images and feed results as context to a text-based query. --- ## Advanced Component Connections Learn how to connect pipeline components in cases that go beyond simple matching. This includes handling incompatible connections or setting up complex routing. *** ## Connecting Two LLMs You can connect two LLMs directly to each other. This is useful when you want to use the output of one LLM as the input for another LLM. Make sure there is a placeholder in the prompt template of the second LLM for the output of the first LLM. Let's say you're building a pipeline that summarizes and simplifies complex contracts, such as bank loan contracts. The pipeline could include these steps: 1. Summarize the contract: The first LLM summarizes the contract. 2. Simplify the language: The second LLM simplifies the summarized contract. The pipelines configuration could look like this: 1. The `Input` component receives the contract text and sends it to the first `LLM` component. 2. The first `LLM` component generates a summary of the contract and sends it to the second `LLM` component. 3. The second `LLM` component receives the summary and simplifies the language. 4. The `Output` component receives the simplified contract and outputs it. #### Example Pipeline Flow
YAML configuration ```yaml components: LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are an expert at explaining complex topics to children. Your task is to rewrite this contract summary so that a 6th grader (11-12 years old) can understand it. Here is the contract summary: {{ summary[0] }} Follow these rules when simplifying the summary: 1. LANGUAGE RULES - Use simple words that a 6th grader knows - Keep sentences short (15 words or less) - Use active voice instead of passive voice - Replace legal terms with everyday words - Define any complex words you must use - Use "you" and "they" instead of formal names when possible 2. EXPLANATION STYLE - Start each section with "This part is about..." - Use real-life examples that kids understand - Compare complex ideas to everyday situations - Break long explanations into smaller chunks - Use bullet points for lists - Add helpful "Think of it like..." comparisons 3. ORGANIZATION - Group similar ideas together - Use friendly headers like "Money Stuff" instead of "Financial Terms" - Put the most important information first - Use numbered lists for steps or sequences - Add transition words (first, next, finally) 4. MAKE IT RELATABLE - Compare contract parts to things kids know: * Compare deadlines to homework due dates * Compare payments to allowance * Compare obligations to classroom rules * Compare penalties to time-outs * Compare termination to quitting a sports team 5. REQUIRED SECTIONS Simplify each of these areas: - Who is involved (like players on a team) - What each person must do (like chores) - Money and payments (like saving allowance) - Important dates (like calendar events) - Rules everyone must follow (like game rules) - What happens if someone breaks the rules - How to end the agreement - How to solve disagreements 6. FORMAT YOUR ANSWER LIKE THIS: "Hi! I'm going to explain this contract in a way that's easy to understand. Think of a contract like a written promise between people or companies. [Then break down each section with simple explanations and examples] Remember: Even though we're making this simple, all parts of the original summary must be included - just explained in a kid-friendly way!" IMPORTANT REMINDERS: - Don't leave out any important information just because it's complex - Double-check that your explanations are accurate - Keep a friendly, encouraging tone - Use emoji or simple symbols to mark important points (⭐, 📅, 💰, ⚠️) - Break up long paragraphs - End with a simple summary of the most important points Your goal is to make the contract summary so clear that a 6th grader could explain it to their friend. Imagine you're the cool teacher who makes complicated stuff fun and easy to understand! {% endmessage %} required_variables: "*" streaming_callback: LLM_2: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a legal document analyzer specializing in contract summarization. Your task is to analyze and summarize the following contract comprehensively. Contract to analyze: {{ contract }} Provide a structured summary that includes ALL of the following components: 1. BASIC INFORMATION - Contract type - Parties involved (full legal names) - Effective date - Duration/term of contract - Governing law/jurisdiction 2. KEY OBLIGATIONS - List all major responsibilities for each party - Highlight any conditional obligations - Note any performance metrics or standards - Identify delivery or service deadlines - Specify any reporting requirements 3. FINANCIAL TERMS - Payment amounts and schedules - Currency specifications - Payment methods - Late payment penalties - Price adjustment mechanisms - Any additional fees or charges 4. CRITICAL DATES & DEADLINES - Contract start date - Contract end date - Key milestone dates - Notice period requirements - Renewal deadlines - Termination notice periods 5. TERMINATION & AMENDMENTS - Termination conditions - Early termination rights - Amendment procedures - Notice requirements - Consequences of termination 6. WARRANTIES & REPRESENTATIONS - List all warranties provided - Duration of warranties - Warranty limitations - Representations made by each party - Disclaimer provisions 7. LIABILITY & INDEMNIFICATION - Liability limitations - Indemnification obligations - Insurance requirements - Force majeure provisions - Exclusions and exceptions 8. CONFIDENTIALITY & IP - Scope of confidential information - Duration of confidentiality - Intellectual property rights - Usage restrictions - Return/destruction requirements 9. DISPUTE RESOLUTION - Resolution process - Arbitration requirements - Mediation procedures - Jurisdiction - Governing law 10. SPECIAL PROVISIONS - Any unique or unusual terms - Special conditions - Specific industry requirements - Regulatory compliance requirements - Any attachments or referenced documents Format your response as follows: - Use clear headings for each section - Use bullet points for individual items - Bold any critical terms, dates, or amounts - Include section references from the original contract - Note if any standard section appears to be missing from the contract IMPORTANT GUIDELINES: - If any of the above sections are not present in the contract, explicitly note their absence - Flag any unusual or potentially problematic clauses - Highlight any ambiguous terms that might need clarification - Include exact quotes for crucial legal language - Note any apparent gaps or inconsistencies in the contract - Identify any terms that appear to deviate from standard industry practice The summary must be comprehensive enough to serve as a quick reference for all material aspects of the contract while highlighting any areas requiring special attention or clarification. {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: LLM_2.last_message receiver: LLM.summary max_runs_per_component: 100 metadata: {} inputs: messages: - LLM_2.contract outputs: messages: LLM.messages ```
## Merging Multiple Outputs With [smart connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections), components can accept connections from multiple lists of the same type. This means you no longer need `DocumentJoiner` or `ListJoiner` in most cases. For step-by-step instructions, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). If you still need to merge outputs in a specific way, you can use a component from the Joiners group. Options include `AnswerJoiner`, `DocumentJoiner`, `BranchJoiner`, and `StringJoiner`. ## Routing Data Based on a Condition You can route a component’s output to different branches in your pipeline based on specific conditions. The `ConditionalRouter` component handles this by using rules that you define. The conditions for routing are specified in the `ConditionalRouter`’s `routes` parameter. Each route includes the following elements: - **`condition`**: A Jinja2 expression that determines if the route should be used. - **`output`**: A Jinja2 expression that defines the data passed to the route. - **`output_name`**: The name of the route output, used to connect to other components. - **`output_type`**: The data type of the route output. Imagine a pipeline that: 1. Uses an LLM to answer user queries based on provided documents. 2. Falls back to a web search if the LLM cannot find an answer. You would need two routes: - One for queries the LLM cannot answer (`no_answer` is present). - One for queries the LLM can answer based on the documents. This is how you could configure the routes: ```yaml - condition: '{{"no_answer" in replies[0]}}' output: '{{ query }}' output_name: search_internet output_type: str - condition: '{{"no_answer" not in replies[0]}}' output: '{{ replies }}' output_name: answer output_type: typing.List[str] ``` The first route is used if `no_answer` appears in the LLM’s replies. This route outputs the query and is labeled `search_internet`. The second route is used if `no_answer` is not present. This route outputs the LLM’s replies and is labeled `answer`. In this setup: - An `LLM` is configured to reply with `no_answer` if it cannot find an answer based on the documents. - The `ConditionalRouter` checks the LLM's reply and decides: - If the reply contains `no_answer`, the query is sent to the `SerperDevWebSearch` component to search the internet for an answer. - If `no_answer` is not present, the reply is sent to the `AnswerBuilder` to format and output the LLM's response. This is what this part of the pipeline configurationcould look like:
YAML configuration ```yaml components: SerperDevWebSearch: # to use this component, you need a SerperDev API key type: haystack.components.websearch.serper_dev.SerperDevWebSearch init_parameters: api_key: type: env_var env_vars: - serper_dev strict: false top_k: 5 allowed_domains: search_params: ConditionalRouter: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: routes: - condition: '{{"no_answer" in replies[0]}}' output: '{{ query }}' output_name: search_internet output_type: str - condition: '{{"no_answer" not in replies[0]}}' output: '{{ replies }}' output_name: answer output_type: typing.List[str] custom_filters: {} unsafe: false validate_output_type: false OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine index: Standard-Index-English-EU-Demo-Schengen max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true timeout: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: false AnswerJoiner: type: haystack.components.joiners.answer_joiner.AnswerJoiner init_parameters: join_mode: concatenate top_k: sort_by_score: false AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: AnswerBuilder_1: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: SentenceTransformersTextEmbedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false truncate_dim: model_kwargs: tokenizer_kwargs: config_kwargs: precision: float32 LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} Answer the following query given the documents. If the answer is not contained within the documents reply with 'no_answer' Query: {{query}} Documents: {% for document in documents %} {{document.content}} {% endfor %} {% endmessage %} required_variables: "*" streaming_callback: LLM_2: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} Answer the following query given the documents retrieved from the web. Your answer shoud indicate that your answer was generated from websearch. Query: {{query}} Documents: {% for document in documents %} {{document.content}} {% endfor %} {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: AnswerBuilder.answers receiver: AnswerJoiner.answers - sender: AnswerBuilder_1.answers receiver: AnswerJoiner.answers - sender: SentenceTransformersTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding - sender: OpenSearchEmbeddingRetriever.documents receiver: LLM.documents - sender: LLM.messages receiver: ConditionalRouter.replies - sender: SerperDevWebSearch.documents receiver: LLM_2.documents - sender: ConditionalRouter.search_internet receiver: LLM_2.query - sender: LLM_2.messages receiver: AnswerBuilder_1.replies - sender: ConditionalRouter.answer receiver: AnswerBuilder.replies max_runs_per_component: 100 metadata: {} inputs: query: - ConditionalRouter.query - AnswerBuilder.query - AnswerBuilder_1.query - SerperDevWebSearch.query - SentenceTransformersTextEmbedder.text - LLM.query outputs: answers: AnswerJoiner.answers ```
--- ## Pipeline Components # Pipeline Components Overview Components are the fundamental building blocks of your pipelines, dictating the flow of data. Each component performs a designated task on the data and then forwards the results to subsequent components. *** ## How Components Work Components receive predefined inputs within the pipeline, execute a specific function, and produce outputs. For example, a component may take files, convert them into embeddings, and pass these embeddings on to the next connected component. You have the flexibility to mix, match, and interchange components in your pipelines. Components are often powered by language models, like LLMs or transformer models, to perform their tasks. :::tip GPU Acceleration By default, components run on CPU. You can turn on GPU acceleration in the pipeline or index settings to speed up processing. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). ::: ## Connecting Components: Inputs and Outputs Components accept specific inputs and produce defined outputs. You can connect components with matching intputs and outputs types. The output type from one component must be compatible with the input type of the subsequent one. For example, a retriever outputs `List[Document]` and a ranker accepts `List[Document]` as input, their types match so you can connect them. Builder guides you through the connections with connection validation. You can also use the Connections panel at the bottom of the canvas to manage, inspect, and edit component connections. To connect components, drag a line between them or use the Connections panel. A component must always receive all of its required inputs. Components that accept lists as inputs can receive multiple outputs if they are of the same type. For example, you can connect multiple Converters that produce lists of documents to a `DocumentWriter` that accepts a list of documents as input. For details, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). When working in YAML, you indicate their output and input names, for example: ```yaml # ... connections: - sender: retriever.documents receiver: ranker.documents # ... ``` The output of the sender component can have a different name than the input of the receiver component as long as their types match, as in this example: ```yaml # ... connections: - sender: file_type_router.text/plain receiver: text_converter.sources # ... ``` For detailed specifications on what inputs and outputs each component requires and generates, refer to the individual documentation pages for each component. The component's inputs and outputs are listed under *Parameters*: ## Configuring Components ### In Builder In Builder, you simply add components to the canvas from the component library that opens when you click **Add**. You can then click the component to open its configuration panel and customize parameters. You can change the component name by clicking it and typing in a new name. ### In YAML The easiest way is to add the component to the canvas in Builder and then switch to the YAML editor to update the component's definition. This is an example of how you can configure a component in the YAML: ```yaml components: my_component: # this is a custom name type: haystack.components.routers.file_type_router.FileTypeRouter # this is the component type you can find in component's documentation init_parameters: {} # this uses the default parameter values ``` #### Connecting Components As components can have multiple outputs, you must explicitly indicate the component's output you want to send to another component. You configure how components connect in the `connections` section of the YAML, specifying the custom names of the components and the names of their output and input you want to connect, as in this example: ```yaml connections: # we're connecting the text/plain output of the sender to the sources input of the receiver component - sender: my_component.text/plain receiver: text_converter.sources ``` If a component accepts outputs from multiple components, you explicitly define each connection, as in this example: ```yaml connections: - sender: embedding_retriever.documents receiver: joiner.documents - sender: bm25_retriever.documents. receiver: joiner.documents ``` ## Component Types Components are grouped by their function, for example, embedders, generators, and so on. Read about what the different types do to help you find appropriate components. ### Embedders Embedders convert text strings or `Document` objects into vector representations (embeddings). They use pre-trained models to do that. Embeddings are vector representations of text that capture the context and meaning of words, rather than just relying on keywords. In LLM apps, they speed up processing and improve the model's ability to understand complex linguistic nuances and semantic understanding of text. #### Text and Document Embedders There are two types of embedders: text and document. Text embedders work with text strings and are most often used at the beginning of query pipelines to convert query text into vectors and send it to a retriever. Document embedders embed Document objects and are most often used in indexing pipelines, after converters, and before DocumentWriter. You must use the same embedding model for text and documents. This means that if you use `CohereDocumentEmbedder` in your indexing pipeline, you must then use `CohereTextEmbedder` with the same model in your query pipeline. ### LLM `LLM` replaces the legacy `Generators` and `ChatGenerators` components. It lets you use large language models (LLMs) in your applications. #### Generators and ChatGenerators :::important Legacy approach Using a `ChatGenerator` with a `ChatPromptBuilder` or a `Generator` with `PromptBuilder` is a legacy approach and will be deprecated in future releases. We recommend using the `LLM` component instead. It replaces both components and works with any LLM provider. For details, see [LLM](/docs/reference/pipeline-components/ai/LLM.mdx). ::: - Generators are designed for text-generation tasks, such as in a retrieval augmented generation (RAG) system, where the user asks a question and receives a one-time answer. Most `Generators` have a corresponding `ChatGenerator`. - ChatGenerators handle multi-turn conversations, maintaining context and consistency throughout the interaction. They also support tool calling, which allows the model to make calls to external tools or functions. #### Key Differences | | Generators | ChatGenerators | |---|---|---| | **Input type** | String (supports Jinja2 syntax) | List of `ChatMessage` objects or `string` | | **Output type** | Text | `ChatMessage` or `string` | | **Best for** | • Single-turn text generation• RAG-style Q&A | • Multi-turn chat scenarios• Maintaining context across interactions• Assuming a consistent role• Tool calls• Using various content types, such as text and images, in prompts | | **Tool calling** | Not supported | Supported (accepts tools and functions as parameters) | | **Used with** | `PromptBuilder` | `ChatPromptBuilder` | #### When to Use Each - Use a ChatGenerator if: - Your application involves multi-turn conversations. - The model needs to call external tools or functions. - You want to use various content types in the prompt, for example images and text. - Use a Generator if the model only needs to generate answers without maintaining conversation history. #### Choosing a Generator Each model provider or model-hosting platform supported by has a dedicated Generator. Choose the one that works with the model provider you want to use. For example, to use the Claude model through Anthropic's API, choose `AnthropicGenerator`. To use models through Amazon Bedrock, choose `AmazonBedrockGenerator`. For guidance on models, see [Language Models in Haystack Enterprise Platform](/docs/concepts/language-models-in-deepset-cloud.mdx). ### ChatMessage `ChatMessage` is a data class used by, `ChatGenerators` and `ChatPromptBuilder`. `ChatPromptBuilder` sends a list of `ChatMessages` to a `ChatGenerator`, which then also returns a list of `ChatMessages`. `LLM`'s prompt is a list of `ChatMessages`. Each message has a role (such as system, user, assistant, or tool) and associated content. The system message is used to set the overall tone and instructions for the conversation, for example: "You are a helpful assistant." The user message is the input from the user, usually a query, but it can also include documents to pass to the model. During the interaction, the LLM generates the next message in the conversation, usually as an assistant. For details on the message format and its properties, see [ChatMessage in Haystack documentation](https://docs.haystack.deepset.ai/docs/chatmessage). When using `ChatPromptBuilder` always provide your instructions using the `template` parameter in the following format: In most cases, you'll write your instructions using the `text` content type and roles such as `user`, `system`, `assistant`, or `tool`. For instance, you might include the model's instructions as a `system` role `ChatMessage`, and the user's input as a `user` role `ChatMessage`. The following example includes retrieved documents within the user message together with the query: ```yaml - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Question: {{ query }} _role: user ``` If the LLM calls a tool, it outputs a message with the content type `tool_call`. You can use this content type to configure conditional pipeline paths. For example, you can create two routes with `ConditionalRouter`: one route for when the LLM makes a tool call, and another for when it doesn't. #### Automatic Type Conversion Connections between `String` and `ChatMessage` are automatically converted in both directions. This means you can connect a `ChatGenerator` to inputs that expect plain text, or pass a query directly to a `ChatGenerator`, without any extra conversion steps. When a `ChatGenerator` receives a `string` input, it automatically converts it to a `ChatMessage` with the user role. When a `ChatMessage` output is connected to a `string` input, its `text` attribute is automatically extracted. If there is no text, the pipeline raises an error. #### Jinja2 Syntax in ChatPromptBuilders You can pass ChatMessages as Jinja2 strings in the `template` parameter of `ChatPromptBuilder`. This makes it possible to create structured ChatMessages with mixed content types, such as images and text. It also makes it possible to test the prompt in Prompt Explorer. Use the `{% message %}` tag to include the `ChatMessage` in the prompt. For example: ```text {% message role="system" %} You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. {% endmessage %} ``` For details, see [ChatPromptBuilder](/docs/reference/pipeline-components/legacy-components/ChatPromptBuilder.mdx) and [Writing Prompts in Haystack Enterprise Platform](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). #### Generators in a Pipeline - Generators receive the prompt from `PromptBuilder` and return a list of strings. They can easily connect to any component that accepts a list of strings as input. - ChatGenerators receive prompts from `ChatPromptBuilder` in the form of a list of `ChatMessage` objects or templatized Jinja2 strings and they return a list of `ChatMessage` objects. - If you want a ChatGenerator's output to be the final pipeline output, you can connect it directly to `AnswerBuilder`. With [smart connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections), the pipeline converts `ChatMessage` to `String` automatically, so you no longer need an `OutputAdapter` in most cases. For details, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). For details, see [Common Component Combinations](/docs/concepts/about-pipelines/common-component-combinations.mdx). ### Limitations ChatGenerators work in Prompt Explorer only if you use the Jinja2 syntax in their `template` parameter. If you use ChatMessages, you experiment with prompts using the Configurations feature in the Playground and modify the ChatPromptBuilder's `template` parameter. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). ## Haystack Components Haystack is 's open source Python framework for building production-ready AI-based systems. is based on Haystack and uses its components, pipelines, and methods under the hood. To learn more about Haystack, see the [Haystack website](https://haystack.deepset.ai/). --- ## Auto Loan Payment Chatbot A conversational chatbot pipeline powered by OpenAI’s gpt-4o, designed to assist with missed auto loan payments. It determines the next action based on user queries and chat history. The actions include verifying client details in a Snowflake database, analyzing sentiment, or negotiating payment options. ## Overview This pipeline handles conversations with bank customers about missed auto loan payments. It's a smart customer service system that knows what to do next based on the conversation flow. It automatically chooses the right action based on context while keeping the conversation flowing naturally. It also always maintains a conversation record to stay aware of the context. ### Best For - Automating customer service interactions - Analyzing sentiment and financial details to guide payment negotiations - Generating human-like prompts for client communication - Verifying client information with database integration - Handling payment instructions and escalation scenarios ### Recommended Dataset - Any Snowflake database with an associated schema of tables and columns extracted from `DESCRIBE TABLE`. For details, see [Snowflake documentation](https://docs.snowflake.com/en/sql-reference/sql/desc-table). - Any text data meant to assist with the chatbot's responses. ### Prerequisites - This pipeline uses the gpt-4o model so you'll need an OpenAI API key to use it. (You can also change the Generator's model). - Table descriptions for retrieval: 1. For each table, create a TXT file with its description. The description should be short, one or two sentences is enough. This is meant to help the Retriever find the relevant table. 2. Add the following metadata to each TXT file: `table: table_name" and "table_columns: column_name - data_type`. For example, for a table called COUNTRY, you'd create a description file called COUNTRY.TXT with the following metadata: `{"table": "COUNTRY", "table_columns": "ID - INTEGER\nNAME - VARCHAR\nREGION - VARCHAR"}`. 3. Upload table descriptions to to the same workspace where the pipeline is. For details, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). ### Potential Applications Automated customer support system. ### How It Works 1. The system analyzes the conversation and decides what action to take. It can choose from seven paths: start call, user verification, sentiment analysis, information extraction, negotiation logic, payment handling, or escalation and handoff. Components involved: `root_prompt_builder`, `root_llm`, `conditional_router` 2. It then proceeds with handling the selected action: 1. Start call: Creates the initial greeting and asks for verification information. Components involved: `inititate_call_prompt_builder`, `initiate_call_llm`, `initiate_call_answer_builder` 1. User verification: Verifies the information the customer provided against a Snowflake database. Then, it either confirms their identity or asks for correct information. Components involved: `verification_prompt_builder`, `verification_llm`, `verification_success_adapter`, `client_database`, `verification_router`, `verification_success_prompt_builder`, `verification_success_llm`, `verification_success_answer_builder`, `verification_fail_prompt_builder`, `verification_fail_adapter`, `verification_fail_answer_builder` 2. Sentiment analysis: Reads the customer's messages to understand their mood and adjusts the conversation tone accordingly. Components involved: `sentiment_prompt_builder`, `sentiment_llm`, `sentiment_answer_builder` 3. Information extraction: Focuses on details about the customer's financial situation, such as when they can pay or how much they can afford. Components involved: `info_extract_prompt_builder`, `info_extract_llm`, `info_extract_answer_builder` 4. Negotiation logic: Handles discussions about payment options and tries to find solutions that work for both the bank and the customer. Components involved: `negotiation_prompt_builder`, `negotiation_llm`, `negotiation_answer_builder` 5. Payment handling: Processes the actual payment arrangements and provides payment links. Components involved: `payment_prompt_builder`, `payment_llm`, `payment_answer_builder` 6. Escalation: Handles situations where a human needs to take over and ensures a smooth handoff to human support. Components involved: `escalation_prompt_builder`, `escalation_llm`, `escalation_answer_builder` ## Pipeline YAML ````yaml components: root_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are part of a chatbot. You receive a question (Current Question) and a chat history. Analyze the following chat history between a client and deepset bank and decide the most appropriate action to take next. The response may include indications of the client's sentiment, willingness to pay, or specific details about their financial situation. Based on the chat history, select one of the following actions as the next step in the process: Start: If the client has not been authenticated. This should always be the first step. User Verification: If the client provides their first name, last name and account number for verification. Sentiment Analysis: If sentiment cues (e.g., frustration, relief) need to be evaluated to guide the negotiation tone. Information Extraction: If specific financial details (e.g., the ability to pay, amount, timing, or payment preferences) need to be identified. Negotiation Logic: If the client shows willingness to negotiate or requests information about possible payment plans. Payment Handling: If the client agrees to make a payment immediately. Escalation & Handoff: If the client expresses frustration, asks for human assistance, or the conversation has not progressed. Your answer must be one of the following actions: - Start Call - User Verification - Sentiment Analysis - Information Extraction - Negotiation Logic - Payment Handling - Escalation & Handoff Context: {{ question }} Next action: root_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0.0 seed: 0 conditional_router: # Conditional router to determine the next action based on the client's response type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: routes: - condition: '{{replies[0].lower() == ''start call''}}' output: '{{ question }}' output_name: call output_type: str - condition: '{{replies[0].lower() == ''user verification''}}' output: '{{ question }}' output_name: verification output_type: str - condition: '{{replies[0].lower() == ''sentiment analysis''}}' output: '{{ question }}' output_name: sentiment output_type: str - condition: '{{replies[0].lower() == ''negotiation logic''}}' output: '{{ question }}' output_name: negotiation output_type: str - condition: '{{replies[0].lower() == ''escalation & handoff''}}' output: '{{ question }}' output_name: escalation output_type: str - condition: '{{replies[0].lower() == ''information extraction''}}' output: '{{ question }}' output_name: extract output_type: str - condition: '{{replies[0].lower() == ''payment handling''}}' output: '{{ question }}' output_name: payment output_type: str unsafe: false # Components for initiating the call initiate_call_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a chatbot calling a client to verify their account numbers before discussing missed auto loan payments. Your name is Deepset, and you work for Deepset Bank as a customer service agent. Instructions: - Your role is to generate a prompt asking the client to verify their first and last name, along with their account number. - This is a one-way discussion; the only questions should be to verify the account number and the client’s first and last name. - Make sure you sound as human as possible when generating the prompt. {{ question }} initiate_call_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 1000 temperature: 0.0 seed: 0 initiate_call_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # Authentification components verification_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are an SQL expert. Your task is to extract the client's first name, last name, and account number from the following text {{ text }}. After identifying the name and account number, add them to the WHERE clause in the SQL template below. If you cannot identify the client's name in this text, respond with an empty string "". Your only goal is to provide the SQL template with the appropriate name or an empty string without any explanation. SQL template: SELECT * FROM CAR_LOAN_DB.WRITEOFF.CUSTOMERS WHERE CLIENT_NAME = AND ACCOUNT_NUMBER = LIMIT 1; You must provide only the SQL query in plain text, as non-SQL characters will break the database. Your answer must not include ```sql or ```. If you cannot identify the client in this text, respond with an empty string "". verification_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 1000 temperature: 0.0 seed: 0 client_database: # This is meant to access client information stored in Snowflake, from which the LLM will verify the information that the customer provided. type: deepset_cloud_custom_nodes.retrievers.snowflake_retriever.DeepsetSnowflakeRetriever init_parameters: user: "" account: "" warehouse: "" verification_success_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: str verification_router: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: routes: - condition: '{{ dataframe.shape[0] == 0 }}' output: '{{ table }}' output_name: fail output_type: str - condition: '{{ dataframe.shape[0] > 0 }}' output: '{{ table }}' output_name: success output_type: str unsafe: false verification_fail_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- I'm sorry, but I couldn't find a match for your first name, last name, and account number in our system. Could you please double-check the information and provide it again? This will help us ensure we're connecting to the correct account. Thank you for your patience! {{ table }} verification_fail_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ [prompt] }}' output_type: typing.List[str] verification_success_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at Deepset Bank responsible for negotiating auto loan payments with clients who have missed their payments. Your task is to verify client details against the bank's records and start the discussion around paying the missed car loan payments. Use the chat history below for guidance and context. Instructions: - Verify the user's identity by confirming their first name, last name, and account number. - Extract critical financial information from the table and ask the user if they would like to make the missed payment. - Provide them with an update on their loan, including details about the car, the loan amount, and the remaining balance to pay off the loan. - Remember, the generated prompt will be used for a text-to-speech system, so you should sound like a human. It's important to consider that the client you are discussing with has missed their payment. Bank's records: {{ table }} Chat history: {{ question }} Prompt: verification_success_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 verification_fail_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm verification_success_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm verification_answer_builder_joiner: type: haystack.components.joiners.answer_joiner.AnswerJoiner init_parameters: {} # Components for detecting clients' sentiment sentiment_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at Deepset Bank responsible for negotiating auto loan payments with clients who have missed their payments. You have been provided with the chat history and the client's current question below to help you achieve your goal. Instructions: - Analyze the client's response in the chat history for emotional cues. - Assess whether the sentiment is positive, neutral, or negative, and determine if the client is receptive, resistant, frustrated, or cooperative regarding commitment to payment or a payment arrangement. Remember, the generated prompt will be used for a text-to-speech system, so you should sound like a human. It's important to consider that the client you are discussing with has missed their payment. It is also important to remember that you are already on the call with the client. The chat history below refers to the previous conversation. That said, do not act as if this is the first time you are talking to the client. {{ question }} Prompt: sentiment_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 sentiment_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # components for conducting the payment negotiation negotiation_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at Deepset Bank responsible for negotiating auto loan payments with clients who have missed their payments. You have been provided with the chat history and the client's current question below to help you achieve your goal. Instructions: - Generate a response based on the client’s sentiment and willingness to discuss payment options, aiming to reach a mutually agreeable payment solution. - Adjust your tone according to the client’s responses. The response should maintain a respectful tone and be solution-oriented, encouraging the client toward a payment commitment that meets their current capacity. It's important to consider that the client you are discussing with has missed their payment. Remember that you are already on the call with the client. The chat history below refers to the previous conversation, so do not act as if this is the first time you are talking to the client. {{ question }} Prompt: negotiation_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 negotiation_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # Components for escalations and handoffs escalation_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at Deepset Bank responsible for negotiating auto loan payments with clients who have missed their payments. You have been provided with the chat history and the client current question below to help you achieve your goal. Instructions: - The client’s response suggests they may need additional assistance from a human representative. - Based on the tone of their message (e.g., frustration, confusion, or request for direct help), generate a response that politely acknowledges their concerns and reassures them that they will be connected with a team member who can help. - Ensure the message conveys empathy and appreciation for their patience, maintaining a supportive and professional tone during the handoff." Example response: "Thank you for your patience, [Client’s Name]. I understand that this might be a bit complex, so I’m connecting you with a team member who can assist further. We appreciate you working with us, and someone will be with you shortly to make sure your concerns are https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.documented." It's important to consider that the client you are in discussion with has missed their payment. It is also important to remember that you are already on the call with the client. The chat history below refers to the previous conversation. That said, do not act as if this is the first time you are talking to the client. {{ question }} Prompt: escalation_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 escalation_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # Components for extracting relevant financial details info_extract_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at Deepset Bank, responsible for negotiating auto loan payments with clients who have missed their payments. You have been provided with the chat history and the client's current question below to help you achieve your goal. Instructions: - Analyze the client’s response and extract relevant financial details that can guide the negotiation process. - Look for information such as the client's ability or willingness to pay, along with specific payments. It is important to consider that the client you are discussing with has missed their payment. It is also essential to remember that you are already on the call with the client. The chat history below refers to the previous conversation. That said, do not act as if this is the first time you are talking to the client. Example of extracted information: "The client indicated they can make a partial payment of $100 next week but cannot commit to the full balance at this time." {{ question }} Prompt: info_extract_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 info_extract_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # Component for handling the payment payment_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a customer service agent at deepset Bank responsible for negotiating auto loan payments with clients who have missed their payments. You have been provided with the chat history and the client current question below to help you achieve your goal. Instructions: - Based on the client’s agreement to make a payment or partial payment, generate a message that confirms their willingness and provides instructions for completing the payment. - If they have chosen a specific payment plan, outline the details clearly. Include a secure payment link, and thank the client for their cooperation. - Ensure the tone is positive and appreciative, encouraging a smooth completion of the payment process." Payment Link: "https://www.deepset.ai" Example response: "Thank you for your cooperation, [Client’s Name]! You can complete your payment by following this secure link: [Payment Link]. If you have any questions, please let us know—we’re here to help!” It is also important to remember that you are already on the call with the client. The chat history below refers to the previous conversation. That said, do not act as if this is the first time you are talking to the client. {{ question }} Prompt: payment_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0.0 seed: 0 payment_answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm answer_joiner: type: haystack.components.joiners.answer_joiner.AnswerJoiner init_parameters: {} connections: - sender: root_prompt_builder.prompt receiver: root_llm.prompt - sender: root_llm.replies receiver: conditional_router.replies - sender: conditional_router.call receiver: initiate_call_prompt_builder.question - sender: initiate_call_prompt_builder.prompt receiver: initiate_call_llm.prompt - sender: initiate_call_llm.replies receiver: initiate_call_answer_builder.replies - sender: conditional_router.call receiver: initiate_call_answer_builder.query - sender: conditional_router.verification receiver: verification_prompt_builder.text - sender: verification_prompt_builder.prompt receiver: verification_llm.prompt - sender: verification_llm.replies receiver: verification_success_adapter.replies - sender: verification_success_adapter.output receiver: client_database.query - sender: client_database.table receiver: verification_router.table - sender: verification_router.fail receiver: verification_fail_prompt_builder.table - sender: verification_fail_prompt_builder.prompt receiver: verification_fail_adapter.prompt - sender: verification_fail_adapter.output receiver: verification_fail_answer_builder.replies - sender: client_database.dataframe receiver: verification_router.dataframe - sender: verification_router.fail receiver: verification_fail_answer_builder.query - sender: verification_router.success receiver: verification_success_prompt_builder.table - sender: verification_success_prompt_builder.prompt receiver: verification_success_llm.prompt - sender: verification_success_llm.replies receiver: verification_success_answer_builder.replies - sender: verification_router.success receiver: verification_success_answer_builder.query - sender: verification_success_answer_builder.answers receiver: verification_answer_builder_joiner.answers - sender: verification_fail_answer_builder.answers receiver: verification_answer_builder_joiner.answers - sender: conditional_router.sentiment receiver: sentiment_prompt_builder.question - sender: sentiment_prompt_builder.prompt receiver: sentiment_llm.prompt - sender: sentiment_llm.replies receiver: sentiment_answer_builder.replies - sender: conditional_router.sentiment receiver: sentiment_answer_builder.query - sender: conditional_router.negotiation receiver: negotiation_prompt_builder.question - sender: negotiation_prompt_builder.prompt receiver: negotiation_llm.prompt - sender: negotiation_llm.replies receiver: negotiation_answer_builder.replies - sender: conditional_router.negotiation receiver: negotiation_answer_builder.query - sender: conditional_router.escalation receiver: escalation_prompt_builder.question - sender: escalation_prompt_builder.prompt receiver: escalation_llm.prompt - sender: escalation_llm.replies receiver: escalation_answer_builder.replies - sender: conditional_router.escalation receiver: escalation_answer_builder.query - sender: conditional_router.extract receiver: info_extract_prompt_builder.question - sender: info_extract_prompt_builder.prompt receiver: info_extract_llm.prompt - sender: info_extract_llm.replies receiver: info_extract_answer_builder.replies - sender: conditional_router.escalation receiver: info_extract_answer_builder.query - sender: conditional_router.payment receiver: payment_prompt_builder.question - sender: payment_prompt_builder.prompt receiver: payment_llm.prompt - sender: payment_llm.replies receiver: payment_answer_builder.replies - sender: conditional_router.payment receiver: payment_answer_builder.query - sender: verification_answer_builder_joiner.answers receiver: answer_joiner.answers - sender: initiate_call_answer_builder.answers receiver: answer_joiner.answers - sender: sentiment_answer_builder.answers receiver: answer_joiner.answers - sender: negotiation_answer_builder.answers receiver: answer_joiner.answers - sender: escalation_answer_builder.answers receiver: answer_joiner.answers - sender: info_extract_answer_builder.answers receiver: answer_joiner.answers - sender: payment_answer_builder.answers receiver: answer_joiner.answers max_runs_per_component: 100 metadata: {} inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "conditional_router.question" - "root_prompt_builder.question" - "verification_success_prompt_builder.question" outputs: # Defines the output of your pipeline answers: "answer_joiner.answers" # The output of the pipeline is the generated answers ```` --- ## Pipeline Examples Explore ready-to-use pipeline examples to get started quickly. Some may require an API key for hosted LLMs. Copy them directly to and start using them right away. *** ## Pipelines [Auto Loan Payment Chatbot](../pipeline-examples/auto-loan-payment-chatbot.mdx): A conversational chatbot pipeline powered by OpenAI’s gpt-4o, designed to assist with missed auto loan payments. ## Usage Instructions To use the pipelines in this section: 1. Copy the pipeline YAML. 2. Log in to and go to _Pipelines > Create pipeline > Create empty file_. 3. Give your pipeline a name and click **Create Pipeline**. 4. In Builder, switch to the YAML view. 5. Paste the copied YAML and save your pipeline. --- ## Agent Memory Agents can carry information throughout a single run or across conversations or agent instances. Short-term memory is handled through agent state that stores conversation history and tool results for a single run. Long-term memory is managed by Mem0 and agents can use it to store facts, preferences, or context across multiple conversations and multiple agent instances. ## Agent State State is a centralized storage all tools can read from and write to. It's a structured way to share data between tools and the Agent, maintain conversation history, and store intermediate results for one run. When you call an Agent, the only information it has is what's in the prompt and the data it was trained on. If an Agent has tools and is part of a conversational system, it's useful to give it additional information, such as its past conversations, the tools it has called, and their results. You'll usually also want to allow the Agent to change this data as it goes along or share it between tools. For example, a tool that searches the web for information may need to store the search results in the state so that other tools can use it. Such external data that the Agent can read and modify is called the Agent's state. Information stored in the state is available only during the current run. When the chat ends, the state is cleared. ### Conversation History State automatically stores the conversation history in the `messages` field. This field uses `list[ChatMessage]` type. By default, it appends new messages to the list so that they're included in the conversation history. The stored messages include: - User messages - System messages - LLM responses (including tool calls) - Tool results ### Defining What Data is Stored in State You can define: - What data is stored in the state. You can choose which tool inputs and outputs are stored in the state. - The type of the data. State supports standard Python types: - Basic types: `str`,`int`, `float`, `bool` - Lists: `list`, `list[str]`, l`ist[int]`, `list[Document]` - Union types: `Union[str, int]`, `Optional[str]` - Custom classes and data classes - How the data is merged when it's updated. To learn about how tools interact with Agent state, see [Tools and Agent State](./agent-tools.mdx#tools-and-agent-state). ## Long-Term Memory with Mem0 Conversation history and Agent state are scoped to a single session. When a conversation ends, that data doesn't carry over. For use cases where you want the Agent to remember facts, preferences, or context across multiple conversations, you can add long-term memory backed by [Mem0](https://mem0.ai). Mem0 automatically extracts structured facts from conversations using an LLM, stores them as vector embeddings, and retrieves relevant memories using semantic search. Mem0 memory consists of two tools that work together: - Store memories: Stores information as a long-term memory. - Retrieve memories: Searches past memories relevant to the current conversation. You can add both tools to an agent or just one, depending on your needs. ### Memory Shared Across Agents Memories are scoped by user ID, which the agent passes with every memory operation. Each user gets their own private set of memories, stored and retrieved independently. Even when multiple users interact with the same agent, they never see each other's memories. Memories stored in Mem0 are available to all Agents connected to the same Mem0 account. This means that if you create multiple Agents in your workspace, they will all be able to access the same memories for a given user. ### How It Works When a user sends a message, the Agent can retrieve memories to pull in relevant facts from previous conversations before generating a response. After the conversation, the agent can store new information for future sessions. ### Requirements To use Mem0 memory, you need a [Mem0 API key](https://mem0.ai/docs/getting-started/installation). ### Configuration Options | Option | Description | |--------|-------------| | Mem0 API key | The workspace secret that holds your Mem0 API key. The same key is used for both tools. | | Memory writer | Toggle to give the Agent the ability to store memories. | | Memory retriever | Toggle to give the Agent the ability to search past memories. | | Top k (retriever) | The maximum number of memories the retriever returns per call. Defaults to five. | You can also customize the tool names and descriptions shown to the LLM for each sub-tool. ## Chat History Granularity When an agent pipeline runs in a multi-turn conversation, the platform replays past conversation turns to the agent on each new request. You can control how much of the chat history is replayed using the `chat history granularity` setting in the pipeline YAML or through the API. You can choose between two modes: - `QUERY_ANSWER` (default): Only the user's query and the agent's final answer from each past turn are included. This is compact and works well for most conversational use cases. - `ALL_MESSAGES`: Every message from each past turn is included — tool calls, tool results, reasoning steps, and the final answer. Use this mode when the agent needs the full context of previous interactions, for example when follow-up requests depend on which tools were called or what results they returned. ### Chat History Granularity in the Pipeline YAML You can also set the granularity directly in the pipeline YAML configuration under the `history` key: ```yaml history: granularity: all_messages ``` Accepted values are `all_messages` and `query_answer` (lowercase). The pipeline YAML setting acts as a default and is overridden by any value passed explicitly in the API request. ### Priority Order The effective granularity is determined in this order: 1. Explicit value passed in the API request (`chat_history_granularity` field). 2. Value set in the pipeline YAML (`history.granularity`). 3. Default: `QUERY_ANSWER`. --- ## Agent Tools Tools are a way to extend the capabilities of the Agent beyond what the LLM alone can do. They are external services the Agent can call to gather more information or perform actions that are not possible with the LLM alone. The Agent relies on the tools to resolve complex queries that require multiple steps or additional information. ## Available Tools A tool can be: - A pipeline (like a RAG pipeline on local data) - A custom function - An MCP server that lets the Agent access an external service - Mem0 Memory tools that give the Agent long-term memory For instructions on how to add tools to the Agent, see [Configuring Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ### Pipelines as Tools You can use pipelines as tools for your Agent. This lets the Agent run entire pipelines, such as a RAG pipeline on your local data, as part of its workflow. You can use an existing pipeline as a tool or create one from a template. When you add a pipeline as a tool, it becomes a separate copy, detached from the original pipeline. You can still access the original pipeline from the **Pipelines** page and continue using it as you normally would. Any changes you make to the original pipeline don't affect the tool pipeline. You can choose how to handle pipeline inputs and outputs. The Agent can either generate the tool inputs or read them from the its state. Storing outputs in the state makes them available to other tools and components in the agent workflow. Note that the Agent's `state_schema` will be updated automatically accordingly. For details, see [Tools and Agent State](/docs/concepts/ai-agents/agent-tools.mdx#tools-and-agent-state). ### Custom Code as Tools You can turn custom Python functions into tools your Agent can use. This lets you add any functionality you need to your Agent. The function becomes a tool the Agent can call when needed. To add a custom tool, choose `Code` as the tool type. This opens the code editor with an example you can modify. The code must use the `@tool` decorator that automatically converts your function into a tool. Each tool must have a name, description, and parameters. The `@tool` decorator infers the tool name, description, and parameters from the function. The Agent uses the tool's name and description to decide when to use it. Make sure these are clear and specific. When creating your custom tool, use Python's `typing.Annotated` to add descriptions to parameters. This helps the Agent understand what each parameter does. For example, `city: Annotated[str, "the city for which to get the weather"] = "Munich"` describes the `city` parameter as a string and explains what it is for. :::tip AI assistant You can use the AI assistant to generate code for your custom tool. To do this, click the **AI Assistant** button on the tool card and write your request in the prompt. ::: #### Example: Weather Tool This is an example of a weather tool that uses the `@tool` decorator: ```python from typing import Annotated, Literal from haystack.tools import tool @tool def get_weather( city: Annotated[str, "the city for which to get the weather"] = "Munich", unit: Annotated[Literal["Celsius", "Fahrenheit"], "the unit for the temperature"] = "Celsius" ): '''A simple function to get the current weather for a location.''' return f"Weather report for {city}: 20 {unit}, sunny" ``` For detailed instructions on how to add a custom tool, see [Add Custom Code as a Tool](/docs/how-to-guides/building-agents/configuring-agent.mdx#add-custom-code-as-a-tool). ### MCP Servers as Tools MCP servers make it possible to integrate external services into the Agent through the Model Context Protocol (MCP). MCP is protocol that standardizes how AI applications communicate with external tools and services. The MCP tool supports two transport options: - Streamable HTTP for connecting to HTTP servers - Server-Sent Events (SSE) for connecting to servers that support SSE Streamable HTTP sends data in pieces rather than all at once. It's like streaming a video file, you start watching it while the rest is still loading. SSE is one-way communication from the server to . The server pushes real-time updates to the Agent. You can compare it to text message alerts from your bank. Once you subscribe, you get notifications when there's activity. The connections stays open and they push updates to you. Some MCP servers require an authentication token to access the service. You can connect only remote MCP servers. To use a local MCP server, first deploy it to a remote server. For detailed instructions on how to add an MCP tool, see [Add an MCP Tool](/docs/how-to-guides/building-agents/configuring-agent.mdx#add-an-mcp-server-as-a-tool). ### Mem0 Memory Mem0 Memory tools give your Agent long-term memory. Instead of relying only on the current conversation, the Agent can store important facts, preferences, and context, then retrieve them in future conversations. This is useful for building personalized assistants that remember information across sessions. Adding Mem0 Memory to your Agent creates two tools: - **Store Memory** (`store_memory` by default): Stores a piece of information as a long-term memory. The Agent calls this tool to persist facts, user preferences, or context it wants to remember. - **Retrieve Memories** (`retrieve_memories` by default): Searches for memories relevant to a query, or returns all memories when no query is given. The Agent calls this tool when stored context from past conversations could help answer the user. Both tools are backed by the [Mem0](https://mem0.ai) service. You need a Mem0 API key to use them. When you add Mem0 Memory, the API key is stored as a workspace secret. Mem0 Memory tools use the Agent's `state_schema` to inject a `user_id` at runtime. This scopes memories to individual users so that each user's memory is kept separate. The platform configures the `state_schema` automatically when you add the tools. For detailed instructions on how to add Mem0 Memory tools, see [Add Mem0 Memory Tools](/docs/how-to-guides/building-agents/configuring-agent.mdx#add-mem0-memory-tools). ## Choosing the Right Tool Type The type of tool you choose depends on what you want your Agent to do. Each tool type serves different purposes and works best for specific scenarios. Use pipeline tools when: - You need a multi-step workflow that combines several components - You want to provide the Agent with access to your internal data through RAG - The task requires a complex process like retrieval, ranking, and formatting - You want to reuse an existing pipeline you've already built and tested **Examples:** - Use a RAG pipeline to search through company knowledge bases or internal documents - Use a hybrid retrieval pipeline that combines keyword search, semantic search, and reranking - Use a document processing pipeline that converts, splits, and ranks documents Use custom code tools when: - You need custom logic that doesn't exist as a component or pipeline - You want to integrate with APIs or services not yet supported by - The functionality is specific to your use case or business logic - You need simple, focused operations that don't require complex pipelines **Examples:** - Create a weather tool that calls a weather API - Build a calculator tool for specific business calculations - Develop a data formatter that transforms data in a custom way - Create a tool that interacts with your internal systems or databases Use MCP servers tools when: - You need to integrate with external services that provide MCP servers - You want to use third-party tools through a standardized protocol - You need real-time data or continuous updates from external sources - You're working with services that support Model Context Protocol **Examples:** - Connect to deepwiki.org to analyze and explain GitHub repositories - Integrate with services that provide MCP-compatible APIs - Access external databases or knowledge bases through MCP - Connect to monitoring or analytics services that support MCP Use Mem0 Memory tools when: - You want your Agent to remember information across conversations - You're building a personalized assistant that adapts to individual users - You need to persist facts or preferences the Agent learns during a session - You want to scope memories to individual users to keep their data separate **Examples:** - Build a support assistant that remembers a user's preferences and past issues - Create a personal assistant that recalls facts the user has shared previously - Develop an onboarding bot that tracks what a user has already completed ### Combining Multiple Tools You can equip your Agent with multiple tools of different types. This is useful when your Agent needs to handle diverse tasks. For example: - **Repository Explainer**: Use an MCP server tool to access repository data and a custom code tool to format the output - **Support Agent**: Use a pipeline tool to search documentation and custom code tools for specific business logic When combining tools, make sure each tool has a clear, distinct purpose. Give them meaningful names and descriptions so the Agent can decide which tool to use for each task. ## Tool Naming and Descriptions Your tool names and descriptions should be clear and concise, and should describe the tool's capabilities and the data it expects and produces. This helps the Agent understand what the tool does and how to use it. Make sure it's easy for the LLM to differentiate between tools and their functions. ## Tutorials - [Building a Deal Desk Agent with Search and Custom Code](/docs/tutorials/build-agents/tutorial-building-an-agent-with-tools.mdx) — Step-by-step example using a document search pipeline tool and a custom code tool together. - [Building an IT Helpdesk Agent with Multiple Knowledge Bases](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) — Step-by-step example using two document search pipeline tools to route questions between knowledge bases. ## Tools and Agent State Tools can read from and write to the Agent --- ## Agentic Pipelines Agentic pipelines have additional capabilities compared to traditional pipelines. They can have conditional branches or tools the LLM can call to gain additional capabilities. However, these pipelines remain predictable and repeatable. *** ## Overview Unlike AI Agents, agentic pipelines contain a predefined sequence of steps executed in a deterministic way. You can think of them like flowcharts—you define exactly what happens in each step and the pipeline follows that path every time it runs. Even if there are conditional branches or tool calls, you define when and how they happen. Agentic pipelines are best for use cases when you know the optimal path and want to avoid the complexity of an AI Agent. In , you can build agentic pipelines with conditional routing. ## Conditional Routing In this setup, a Generator (an LLM) is paired with a `ConditionalRouter` component. The LLM analyzes incoming data and classifies it, routing the input to the most appropriate pipeline branch. ### How It Works 1. The LLM receives the input data and based on it decides which branch to take. 2. The LLM sends the data to `ConditionalRouter`, which forwards it along the appropriate route. ### Example Use Case The LLM decides whether a query can be answered directly or needs additional data from a local database. It then sends the query to the `ConditionalRouter`, which forwards it along the appropriate route the LLM indicated. ### When To Use It These types of systems are best if: - You need to handle different input types with specialized processing for each type. - You want predictable, transparent behavior with minimal complexity. ### Pros Systems with conditional routing are: - Clear - Controllable - Transparent - Predictable - Easy to debug ### Cons - Limited flexibility compared to agent-based systems - No decision loop or iterative improvements --- ## AI Agent AI Agents are intelligent systems that perform tasks autonomously by reasoning, making decisions, and interacting with external tools. At their core, they rely on LLMs to determine what actions to take. By working with tools like pipelines, or custom functions, Agents can handle tasks far more complex than what traditional chatbots or generative question-answering systems can manage. Agents are particularly useful when tasks require autonomous decision-making and interactions with multiple tools. *** ## Agent Agent is an AI-based system that reasons about actions and executes multi-step tasks autonomously using tools it has at its disposal. Unlike a RAG Chat pipeline, that just answers questions based on the data it has, an Agent can plan ahead, decide which tools it needs, and work through multi-step processes to accomplish a goal. This may sound complex, but an Agent is really an LLM calling tools and executing them in a loop until it reaches a defined exit condition. ### Key Features - **Model-agnostic**: Works with any LLM giving you full flexibility. - **Tool-friendly**: Seamlessly uses external tools like pipelines, custom functions, and MCP servers. - **Stay in control**: Set clear exit conditions so the Agent stops when and how you want. - **Context-aware**: Remembers conversation history and tracks which tools it has used. - **Real-time output**: Supports streaming responses. - **Async-ready**: Handles asynchronous execution to fit into complex workflow. - **Observability**: Connect traces like Langfuse or Weights & Biases Weave to monitor the Agent's behavior in detail. ### Agent vs RAG Chat Both an Agent and a RAG Chat pipeline are LLM-based systems that can act as assistants and answer questions in a chat format. But there are significant differences between the two.- - **RAG Chat** is designed for question answering with retrieval-augmented generation. It’s great when your goal is to ground responses in documents using a Retriever and Reader. It’s simple, fast, and optimized for knowledge-based chats. - **Agent** is built for more complex, dynamic workflows. It can use a variety of tools—like pipelines, custom code, and MCP servers—to decide how to answer. Agents can maintain context, make decisions, and chain multiple steps together. Use **RAG Chat** when you need fast, document-based answers. Use **Agent** when your task involves reasoning, tool use, or multi-step logic. ### Agent's Workflow The Agent follows this general workflow: 1. The Agent receives a user message and sends it to the LLM together with a list of tools. 2. The LLM decides whether to respond directly or call a tool. 1. If the LLM returns an answer, the Agent stops and returns the result. 2. If the LLM returns a tool call, the Agent runs the tool. 3. The Agent receives the tool call result and checks if it matches the exit condition. 1. If it does, the Agent stops and returns all the messages. 2. If it doesn't, the Agent sends the conversation history, including the tool output, back to the LLM and the loop starts over. ## Building Agents in The Agent is available as a pipeline component you can add to your pipelines. It lets you easily choose the underlying model, configure and edit tools on the Agent component card, and connect it to other components that send or receive data. The Agent also has memory that persists across runs, allowing it to track conversation history and the tools it has used. ## Available Pipeline Templates offers multiple Agent templates to help you start building your own Agents. You can find them on the Pipeline Templates page under _Agents_. To use these templates, make sure you meet the prerequisites, as described on each template details page. ## Tutorials - [Building a Deal Desk Agent with Search and Custom Code](/docs/tutorials/build-agents/tutorial-building-an-agent-with-tools.mdx) — Build an agent that searches pricing policy documents and applies deterministic discount approval rules with a custom code tool. - [Building an IT Helpdesk Agent with Multiple Knowledge Bases](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) — Build an agent that routes employee questions to the right knowledge base using two document search pipeline tools. --- ## Data Flow in Haystack Enterprise Platform # Data Flow in Explore the journey of data in , from the moment you upload your files or connect your data storage, through processing, to output. *** ## Where Is My Data? Let's start with what happens to the files when you upload them to and where they are stored. This differs a bit depending on whether you're uploading synchronously or asynchronously. It's also different if you're connecting your own virtual private cloud (VPC), like the AWS S3 bucket. Let's look at all these scenarios. ## Uploading Files All files uploaded to are eventually stored in the AWS S3 bucket. There are two methods for uploading files: synchronous and asynchronous. When you upload synchronously, there's an additional step where the files go through the main API service before they're sent to S3. When you upload asynchronously, using sessions, your files go directly to the S3 bucket. is also connected to a SQL database. This database stores information about files, such as file name, file id, and when it was created. It does not store the contents of the files. When you use your own VPC, like AWS S3 or OpenSearch, to store files, your files remain in your storage at all times. You authorize to communicate with the file storage when it needs to index the files. We'll cover that in _Deploying Pipelines_ in more detail. ## Enabling Indexes When you enable an index, it triggers indexing. Indexing means your files are preprocessed, chunked into pieces of raw text called Documents, and stored in the document store. `OpenSearchDocumentStore` is the default, core document store of m, but you can use any other supported database. During indexing: 1. product fetches the names of files to index from the database. 2. It then communicates these file names to the index. 3. The index fetches the actual files from the data storage and starts indexing. During indexing, the files are temporarily stored in the indexing service. 4. The index preprocesses the files and sends the resulting documents to the document store. After that, the files are deleted from the temporary location. This graphic shows the flow using the example of `OpenSearchDocumentStore`: The process is the same regardless of whether you store your files in or in a private AWS S3 bucket. If you want your data to stay in your accounts, we recommend connecting a private AWS S3 bucket and a private OpenSearch cluster. Otherwise, the documents, which are chunked files, are still stored in OpenSearch. ## Searching Let's examine what happens at search time. Your query goes to the query pipeline, which (more specifically, the Retriever node) connects with the OpenSearchDocumentStore and fetches the documents that match the query. If you use your private OpenSearch cluster, you authorize to connect to it at query time. The query pipeline then reaches out to your OpenSearch cluster to fetch the documents from there. These documents are stored in a temporary memory, not saved anywhere. If it's a question answering pipeline, the Retriever passes the documents on to the Reader or Generator, which comes up with the final answer based on them. The results of the query are stored in the SQL database. The database is protected, and only a selected number of employees can access it. ### Using Hosted Models You can use models hosted by OpenAI, Hugging Face, Cohere, Azure OpenAI, SageMaker, or Amazon Bedrock in your query pipelines. For a full list, see [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). A hosted model is especially useful for large language models requiring substantial infrastructure. To use a hosted model, you first [connect to the model provider](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx) using your credentials. The encrypted credentials are securely stored in the database. When you make a query, sends an HTTP request to the model provider, including your credentials in the request header. If the authorization is successful, the model generates the response and sends it back to . When using a hosted model, remember that your pipeline's stability depends on the model provider. If you disconnect from a model provider, all pipelines using models hosted by this provider stop working. --- ## Document Stores Document store is a database that stores the pre-processed documents resulting from your indexing pipeline. The query pipeline uses retrievers to access the document store and fetch relevant documents to resolve queries. *** ## The Document Store Concept A document store is a Haystack concept that refers to an object that stores your data. It's an interface to a database like OpenSearch, Weaviate, or Pinecone, for storing and retrieving your data. Document store stores data as `Document` objects. Each document has a unique ID, metadata, and can optionally include vector representations (embeddings) for enhanced search capabilities. In , a document store is a parameter of other components, such as a `Retriever` or `DocumentWriter`. To make things easier, document stores appear as component cards in Pipeline Builder. ### Document To store your data in a document store, you must convert them into `Document` objects first. Documents are individual pieces of information that can include text, data frames, or binary data. When an indexing pipeline runs, files uploaded to your workspace are preprocessed, cleaned, split, and converted into `Document` objects using PreProcessor components. One file can be split into multiple documents. Once processed, the `DocumentWriter` component writes them into a document store. Query pipelines work on the documents stored in the document store, not directly on the uploaded files. A Retriever fetches the relevant documents from the document store and passes them to subsequent components in the pipeline to resolve queries or run other tasks. `Document` is a Haystack data class with specific properties you can access. One file may produce multiple documents. Documents inherit metadata from files. For details, see [Haystack documentation for data classes](https://docs.haystack.deepset.ai/docs/data-classes#document). ### Indexes and Document Store In , when building an index, you specify the document store where it writes the data. The index then becomes a parameter of this document store. When configuring the document store, you can choose the index to use from the document store card. ## Writing Documents into the Document Store Index defines how and where you write the resulting document. You can write documents into a document store using DocumentWriter. As a best practice, include `DocumentWriter` as the last component in your index, and make sure it's connected to a document store. ## Retrieving Documents Document stores work with retrievers. Retrievers in your query pipeline access the document store to fetch the documents relevant to the query. Each document store has dedicated retrievers, usually a keyword retriever, a vector retriever, and sometimes a hybrid retriever that combines both. This is because retrievers rely on the document store technology to fetch documents. Connect a `Retriever` to a matching document store to enable it to fetch documents from this document store. ## Configuring a Document Store ### In Pipeline Builder Drag a document store from the Component Library connect it to `DocumentWriter` or a `Retriever`. You can configure the document store parameters on the document store card. For detailed parameter explanation, see [Haystack's Integrations API documentation](https://docs.haystack.deepset.ai/reference/integrations-opensearch). If multiple components in a pipeline need a document store and use the same configuration, you only need to add one document store card. You can then connect this single card to all the components that use it. But if different components require different document store configurations, add a separate document store card for each unique setup. Then, configure each card as needed and connect them to the right components: ### In YAML Pass the document store configuration in the `document_store` parameter of `DocumentWriter` or a `Retriever`: ```yaml bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: #this is the document store configuration type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: default max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: 10 top_k: 20 # The number of results to return fuzziness: 0 ``` ## Supported Document Stores ### Core Document Stores [OpenSearch](https://opensearch.org/docs/latest/about/) OpenSearch is the only core document store of . We manage its infrastructure and credentials and have access to its index and indexing information, such as the detailed status of files being indexed. also manages file updates, including the metadata and deletions, and keeps the document store in sync. ### Integrations These document stores run on your infrastructure, and you're responsible for managing the credentials (you provide them in the configuration). When you deploy your indexing pipeline, creates the index for these document stores, but the number of indexed files will always display as `0`. For integrations, also handles metadata updates and file deletions, ensuring that changes are reflected in the document store. - [Elasticsearch](https://www.elastic.co/elasticsearch) - [MongoDB](https://www.mongodb.com/) - [Pinecone](https://www.pinecone.io/) - [Qdrant](https://try.qdrant.tech/high-performance-vector-search) - [Weaviate](https://weaviate.io/platform) ### Other [Snowflake](/docs/how-to-guides/working-with-your-data/use-snowflake-database.mdx). Snowflake is a table database that doesn't have an index. You can query your Snowflake data using `SnowflakeTableRetriever`, which accesses the database and fetches a table that matches the SQL query. ## Comparison This table compares the document stores in : | Document store | Infrastructure | Index | Indexing status | File updates (deleting, metadata updates) | |----------------|---------------|-------|----------------|------------------------------------------| | OpenSearch | Managed by | Managed by | Shown in details (indexed, skipped, and failed files) | Managed by | | Elasticsearch | Your own | Created on pipeline deployDeleted on pipeline undeploy | No information, always shown as `0` | Managed by | | MongoDB | Your own | You need to create a vector search index in MongoDB | No information, always shown as `0` | Managed by | | Pinecone | Your own (you need to host the database locally) | Created on pipeline deployDeleted on pipeline undeploy | No information, always shown as `0` | Managed by | | Qdrant | Your own | Created on pipeline deployDeleted on pipeline undeploy | No information, always shown as `0` | Managed by | | Snowflake | Your own | Not available (Snowflake doesn't use indexes) | Not available | You're responsible for managing the tables | | Weaviate | Your own | Created on pipeline deployDeleted on pipeline undeploy | No information, always shown as `0` | Managed by | ## Choosing the Right Document Store Have a look at the [Haystack Guide](https://docs.haystack.deepset.ai/docs/choosing-a-document-store) to help you choose the document store that will work best for your scenario. --- ## ElasticsearchDocumentStore Use the Elasticsearch database as your document store. ## Basic Information - Used with the following retrievers: - `ElasticsearchBM25Retriever` - `ElasticsearchEmbeddingRetriever` - Type: `haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore` ## Overview For details, see [ElasticsearchDocumentStore](https://docs.haystack.deepset.ai/docs/elasticsearch-document-store) in Haystack documentation. ## Authorization You need an Elasticsearch account and `cloud_id` and `api_key` to use this document store in Elastic Cloud. You can create a secret for it and then pass it its name in the `api_key` parameter of the document store. To learn more about secrets, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ## Example Configuration ### In an Index To write the preprocessed files into the document store: 1. Add `DocumentWriter` to your pipeline. 2. Add `ElasticsearchDocumentStore` and configure it on the component card. 3. Connect `ElasticsearchDocumentStore` to `DocumentWriter`. ### In a Query Pipeline To retrieve files from the document store: 1. Add an Elasticsearch retriever to your pipeline. 2. Add `ElasticsearchDocumentStore` and configure it on the component card. 3. Connect the document store to the retriever. ### Example This is where you can access the configuration: When you switch to the YAML view, you can see that the document store is an argument of `DocumentWriter` and you can configure it there: ```yaml writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore #document store configuration init_parameters: index: default embedding_similarity_function: cosine policy: OVERWRITE ``` ## Init Parameters To check the parameters you can customize for this document store, see [ElasticsearchDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-elasticsearch#elasticsearchdocumentstore) in Haystack documentation. --- ## MongoDBAtlasDocumentStore Use the MongoDB database as the document store for storing data your pipelines can query. *** ## Basic Information - Used with `MongoDBAtlasEmbeddingRetriever` - Type: `haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore` ## Overview For details, see [MongoDB documentation](https://www.mongodb.com/docs/atlas/) and [Haystack documentation](https://docs.haystack.deepset.ai/docs/mongodbatlasdocumentstore). ## Authorization You must have an Atlas account. For details on setting it up, see [MongoDB documentation](https://www.mongodb.com/docs/atlas/getting-started/?tck=atlas_learn). To connect to the MongoDB database, you must provide a connection string in the format `"mongodb+srv://{mongo_atlas_username}:{mongo_atlas_password}@{mongo_atlas_host}/?{mongo_atlas_params_string}"`. For detailed instructions on how to obtain it, see [Create a Connection String](https://www.mongodb.com/docs/mongoid/current/quick-start-sinatra/create-a-connection-string/) in MongoDB documentation. Once you have your connection string, connect MongoDB to on the Integrations page: 1. Log in to . 2. Click your profile icon in the top right corner and choose *Settings*. 3. Go to *Workspace>Integrations*, find MongoDB, and click **Connect** next to it. 4. Paste your MongoDB connection string and click **Connect**. ## Usage To configure MongoDB as the document store, you need: - The name of the database to use. - The name of the collection to use. This collection must have a vector search index set up on the `embedding` field and a full text search index. - The name of the vector search index to use for vector search. You can create a vector search index on your collection in the Atlas web user interface. **Important**: Your MongoDB vector search index must have an `embedding` field of type `knnVector` defined, for example: ```python const index = { name: "vector_index", type: "vectorSearch", definition: { "fields": [ { "type": "knnVector", "path": "embedding", "similarity": "cosine", "numDimensions": 768 } ] } } ``` This allows you to use embedding retrieval with the MongoDB document store. - The name of the full text search index. You create a full text search index on your collection in the Altas user interface. You must create both a vector search index and a full text search index on your Atlas collection, one for embeddings and one for text. Vector search index is used for embedding-based similarity queries, while the full-text index is used for keyword queries. This way, you can use hybrid search out of the box. For details, see [MongoDB documentation](https://www.mongodb.com/docs/compass/current/indexes/create-vector-search-index/). ### Writing Data to MongoDB To write the preprocessed files into the MongoDB document store: 1. Add `DocumentWriter` to your index. 2. Add `MongoDBAtlasDocumentStore` and configure the required parameters on the component card. You must provide: - `database_name`: The name of your MongoDB database. - `collection_name`: The name of your collection. - `vector_search_index`: The name of the vector search index created on your collection. Make sure the index has an `embedding` field of type `knnVector` defined. 3. Connect `MongoDBAtlasDocumentStore` to `DocumentWriter`. ### Retrieving Files From MongoDB To retrieve files from the MongoDB document store and use them for search: 1. Add a MongoDB Atlas Retriever your query pipeline. 2. Add `MongoDBAtlasDocumentStore` and configure the required parameters on the component card. You must provide: - `database_name`: The name of your MongoDB database. - `collection_name`: The name of your collection. - `vector_search_index`: The name of the vector search index created on your collection. Make sure the index has an `embedding` field of type `knnVector` defined. 3. Connect `MongoDBAtlasDocumentStore` to the Retriever. ### Examples This is how you connect the document store to writer: When you switch to YAML, you can see that the document store is a parameter of `DocumentWriter` and that's where you can configure it as well: ```yaml writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore #document store configuration init_parameters: mongo_connection_string: type: env_var env_vars: - MONGO_CONNECTION_STRING strict: false database_name: myDatabase collection_name: myCollection vector_search_index: vectorIndex full_text_search_index: fullTextIndex policy: OVERWRITE ``` ## Init Parameters | Parameter | Type | Possible values | Description | |--------------------------|---------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `mongo_connection_string` | Secret | | The connection string to connect with MongoDB Atlas. You can obtain it by clicking the **CONNECT** button on the MongoDB Atlas Dashboard. For details, see the _Authorization_ section above. Required. | | `database_name` | String | | The name of your MongoDB Atlas database. Required. | | `collection_name` | String | | The name of the MongoDB Atlas collection you want to use. To use a collection for vector search, it must have a vector search index configured on the `embedding` field. For details, see the _Usage_ section above. Required. | | `vector_search_index` | String | | The name of the MongoDB Atlas vector search index to use for embedding retrieval. Create a vector search index in the Atlas dashboard. For details, see the _Usage_ section above. Required. | | `full_text_search_index` | String | | The name of the text search index to use for keyword retrieval. Create the index in your MongoDB Atlas dashboard. Required. | --- ## OpenSearchDocumentStore The core document store of . *** ## Basic Information - Used with the following retrievers: - `OpenSearchBM25Retriever` - `OpenSearchEmbeddingRetriever` - Type: `haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore` ## Overview For details on how this document store works, see [OpenSearchDocumentStore ](https://docs.haystack.deepset.ai/docs/opensearch-document-store)in the Haystack documentation. ## Authorization This is the core document store of and as such, we handle the authorization. ## Example Configuration ### In an Index To write the preprocesses files into the document store: 1. Add `DocumentWriter` to your pipeline. 2. Add `OpenSearchDocumentStore` and configure it on the component card. 3. Connect `OpenSearchDocumentStore` to `DocumentWriter`. ### In a Query Pipeline To retrieve files from the document store: 1. Add an OpenSearch retriever to your pipeline. 2. Add `OpenSearchDocumentStore` and configure it on the component card. 3. Connect `OpenSearchDocumentStore` to the retriever. ### Example When you switch to YAML, you'll see that the document store is an argument of each retriever: ```yaml components: query_expander: type: haystack.components.query.query_expander.QueryExpander init_parameters: n_expansions: 3 include_original_query: true chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: {} multi_query_retriever: type: haystack.components.retrievers.multi_query_text_retriever.MultiQueryTextRetriever init_parameters: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: # this is the document store configuration type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 5 connections: - sender: query_expander.queries receiver: multi_query_retriever.queries max_runs_per_component: 100 metadata: {} inputs: query: - query_expander.query ``` ## Init Parameters For a list of parameters you can configure, see [OpenSearchDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-opensearch#opensearchdocumentstore) in Haystack documentation. --- ## PgvectorDocumentStore Use Cloud SQL for PostgreSQL hosted on Google Cloud through the PgvectorDocumentStore. ## Basic Information - Used with the following retrievers: - `PgvectorEmbeddingRetriever` - `PgvectorKeywordRetriever` - Needs the `CloudSQLAuthProxy` component to be present in a pipeline to set up the connection with the database. - Type: `haystack_integrations.document_stores.pgvector.document_store.PgvectorDocumentStore` ## Overview ## Init Parameters Check the [PgvectorDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-pgvector#pgvectordocumentstore) in Haystack documentation. --- ## PineconeDocumentStore Use the Pinecone database as your document store. *** ## Basic Information - Used with the following retrievers: - `PineconeEmbeddingRetriever` - Type: `haystack_integrations.document_stores.pinecone.document_store.PineconeDocumentStore` ## Overview For details, see [PineconeDocumentStore](https://docs.haystack.deepset.ai/docs/pinecone-document-store) in Haystack documentation. ## Authorization You need a Pinecone API key to use `PineconeDocumentStore`. You can create a secret for it and then pass it its name in the `api_key` parameter of the document store. To learn more about secrets, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ## Example Configuration ### In an Index To write the preprocesses files into the document store: 1. Add `DocumentWriter` to your pipeline. 2. Add `PineconeDocumentStore` and configure it on the component card. 3. Connect `DocumentWriter` with the document store. ### In a Query Pipeline To retrieve files from the document store: 1. Add a Pinecone retriever to your pipeline. 2. Add `PineconeDocumentStore` and configure it on the component card. 3. Connect the retriever with the document store. ### Example When you switch to YAML, you can see that the document store is an argument of `DocumentWriter` or a retriever: ```yaml writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: # document store configuration type: haystack_integrations.document_stores.pinecone.document_store.PineconeDocumentStore # document store configuration init_parameters: api_key: type: env_var env_vars: - PINECONE_API_KEY strict: false index: default namespace: default batch_size: 100 dimension: 768 metric: cosine policy: OVERWRITE ``` ## Init Parameters To check the parameters you can customize for this document store, see [PineconeDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-pinecone#pineconedocumentstore) in Haystack documentation. --- ## QdrantDocumentStore Use the Qdrant database as your document store. *** ## Basic Information - Used with the following retrievers: - `QdrantEmbeddingRetriever` - `QdrantSparseEmbeddingRetriever` - `QdrantHybridRetriever` - Type: `haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore` :::info Hosting You must host the Qdrant database locally to make it work with . For instructions, see [Qdrant documentation](https://qdrant.tech/documentation/guides/installation/). ::: ## Overview For details, see [QdrantDocumentStore](https://docs.haystack.deepset.ai/docs/qdrant-document-store) in Haystack documentation. ## Authorization To use an API key for your Qdrant database, create a secret for it and then pass it its name in the `api_key` parameter of the document store. To learn more about secrets, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ## Example Configuration ### In an Index To write the preprocessed files into the document store: 1. Add `DocumentWriter` to your pipeline. 2. Add `QdrantDocumentStore` and configure it on the component card. 3. Connect the two components. ### In a Query Pipeline To retrieve files from the document store: 1. Add a Qdrant retriever to your pipeline. 2. Add `QdrantDocumentStore` and configure it on the component card. 3. Connect the document store and the retriever. ### Example When you switch to YAML, you can see that the document store is an argument of `DocumentWriter`. It's the same for retrievers: ```yaml components: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: # document store configuration type: haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore # document store configuration init_parameters: port: 6333 grpc_port: 6334 prefer_grpc: false force_disable_check_same_thread: false index: Document embedding_dim: 768 on_disk: false use_sparse_embeddings: false sparse_idf: false similarity: cosine return_embedding: false progress_bar: true recreate_index: false wait_result_from_api: true write_batch_size: 100 scroll_size: 10000 ``` ## Init Parameters To check the parameters you can customize for this document store, see [QdrantDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-qdrant#qdrantdocumentstore) in Haystack documentation. --- ## WeaviateDocumentStore Use the Weaviate database as your document store. *** ## Basic Information - Used with the following retrievers: - `WeaviateBM25Retriever` - `WeaviateEmbeddingRetriever` - Type: `haystack_integrations.document_stores.weaviate.document_store.WeaviateDocumentStore` ## Overview For details, see [WeaviateDocumentStore](https://docs.haystack.deepset.ai/docs/weaviatedocumentstore) in Haystack documentation. ## Authorization If you're using a paid option, you need a Weaviate account and a `url` and `api_key` to use this document store. You can create a secret for it and then pass it its name in the `api_key` parameter of the document store. To learn more about secrets, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ## Example Configuration ### In an Index To write the preprocesses files into the document store: 1. Add `DocumentWriter` to your pipeline. 2. Add `WeaviateDocumentStore` and configure it on the component card. 3. Connect the components using their `document_store` connection point. ### In a Query Pipeline To retrieve files from the document store: 1. Add a Weaviate retriever to your pipeline. 2. Add `WeaviateDocumentStore` and configure it on the component card. 3. Connect the components using their `document_store` connection point. ### Example When you switch to YAML, you can see that the document store is an argument of `DocumentWriter` or Weaviate retriever: ```yaml DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.weaviate.document_store.WeaviateDocumentStore # document store confguration init_parameters: grpc_port: 50051 grpc_secure: false ``` ## Init Parameters To check the parameters you can customize for this document store, see [WeaviateDocumentStore API reference](https://docs.haystack.deepset.ai/reference/integrations-weaviate#weaviatedocumentstore) in Haystack documentation. --- ## Indexes Indexes preprocess your files preparing them for search and store them in a document store of your choice. You can reuse indexes across your query pipelines. Learn how it works. *** ## What's an Index An index is a data structure that provides your pipelines with fast, efficient access to your large-scale datasets. Think of it as a book index that helps you find specific topics without reading the entire book. It's crucial for fast, efficient search, making it possible to handle large-scale datasets. ## How Indexes Work Indexes work on the files uploaded to . Indexes use configurable components connected together with each one performing a single task on your files, such as conversion, cleaning, or splitting. They clean the files and chunk them into smaller passages called `documents`. Then, they write the cleaned documents in a database called `document store` from which the pipeline retrieves them at query time. Indexes are optional, meaning that if you have a query pipeline that queries files in an existing database, like Snowflake, or uses the model's knowledge, you don't need an index. Indexes are specific to a workspace. Deleting a workspace deletes all the indexes in this workspace. ### Document Stores Document store is where your index writes the data and where your pipelines can then access them. When setting up a pipeline, you can connect it to a document store and choose an index directly from the Document Store component card. For details, see [Document Stores](../document-stores/document-stores.mdx). ### Indexing The files in are indexed once when an index is enabled. New files uploaded after you enable an index are indexed individually and added to the enabled index. ## File Updates You can upload, delete, and modify files if your index is enabled. You can also update the metadata of individual files. Changes apply only to the specific files you modify. For example, when you upload a file, only that file is indexed. doesn't reindex all existing files. ### Metadata Updates When you update a file's metadata, does not reindex the file content. Instead, it follows these steps: 1. It updates the metadata in the workspace index in OpenSearch. 2. It notifies the index, which then updates any documents derived from the file. Any changes to the files are queued and delayed to ensure the correct order. ### Example Let's say you perform these operations on your files: 1. Upload file1.txt. 2. Upload file2.txt. 3. Delete file1.txt. 4. Update metadata of file2.txt. 5. Upload file3.txt. processes it in the following order: 1. Index file1.txt. 2. Index file2.txt. 3. Delete file1.txt. 4. Update documents created from file2.txt with the new metadata. 5. Index file3.txt :::tip Checking the task status Only after the steps are completed and the number of pending tasks is 0, the changes are live and you can view them in . You can check the task status on the Indexes page. Hover your mouse over the status label: You can also use the [Get Index By Name](/docs/api/main/get-index-by-name-api-v-1-workspaces-workspace-name-indexes-index-name-get.api.mdx) endpoint to check the task status. ::: ### Core and Integration Indexes Core indexes write files into the [OpenSearchDocumentStore](/docs/concepts/document-stores/opensearchdocumentstore.mdx), which is the core document store of . This means manages its infrastructure, authorization, and has access to the indexing information. Integration indexes use one of the integrated document stores, such as Pinecone, Weaviate, or others. For these document stores, you must manage the infrastructure yourself. also doesn't have access to the indexing information. For details, see [Document Stores](../document-stores/document-stores.mdx). ### Indexes and Pipelines To run searches on files in , a pipeline must be connected to an index. You do this by adding a document store to a query pipeline and choosing the index you want this document store to use. Multiple pipelines can use a single index; one pipeline can use multiple indexes. An index must be enabled to be used in a query pipeline. ## Building Indexes provides a set of curated and maintained index templates for various file types. You can use one of the templates to build your index or you can start from scratch. Indexes are built the same way as query pipelines. You simply drag components to the canvas in Pipeline Builder and then connect them so that the output of the preceding component matches the input type of the next component. For details, check _How do pipelines work_ in [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). ### Input Indexes always start with an `Input` component. When in Builder, add the `Input` component at the beginning of an index. ### Outputs Indexes return a list of `Document` objects as output, usually written into the document store by the `DocumentWriter` component, which is often the last component in an index. ### Body The index body defines what happens with the files you uploaded to . It's up to you how you want to process your files. For hints and best practices, see [PreProcessing Data with Pipeline Components](/docs/how-to-guides/working-with-indexes/prepare-your-data.mdx). ### Enabling Indexes To start indexing, you enable an index from the Indexes page. An enabled index is in view-only mode, so you can't edit it. To make changes, you disable the index first. However, you can't disable an index that's used by a deployed pipeline. In this case, you can duplicate the index and update the copy. To deploy a query pipeline, you must enable all indexes used by this pipeline. ## Using Indexes in Query Pipelines Indexes are linked to a document store, where documents are written and stored. Pipelines that work with your data include Retrievers, which fetch data from the document store. When setting up a Retriever, you need to connect it to a document store. After that, you can select an index from the document store card. This index is the one your query pipeline will use to search and retrieve data from the document store. To use multiple indexes in a single query pipeline, create a separate document store for each index. Then, assign a retriever to each document store, since a retriever can only be connected to one document store at a time. ## The Indexes Page The Indexes page lists all indexes that exist in a workspace and their status. There are two tabs on the page: - **Active**, for enabled indexes - **Drafts**, for indexes that were saved but not yet enabled ## The Index Details Page Click an index name to open the Index Details Page where you can check: - The index ID - The status of files this index processes - Details of pipelines connected to this index - Index logs - Settings ### File Statistics You can see the following statistics for the files in the index: - Total files - Indexed files: The number of files successfully indexed into the document store. - Documents in index: The cumulative total of documents stored in the document store across all indexing runs. - Pending tasks: The count of ongoing indexing tasks, like adding files to the document store or updating metadata. - Skipped files: The number of files that were processed but produced no documents. - Failed files: The count of files that encountered errors during indexing. ### Settings #### GPU Acceleration Indexes use CPU by default. Turn on GPU support on the Settings tab when your index includes components that run better on a GPU, such as `DoclingConverter`, `SentenceTransformersDocumentEmbedder`, or custom components that use AI models. When GPU support is on, the index checks whether a component needs a GPU and assigns one automatically. GPUs are only used when required and are not reserved for the entire index run. If GPU support is off and your index includes components that rely on a GPU, those components run on the CPU instead. This can slow down processing and may cause timeouts, especially for larger or more complex indexes. For details on how to enable GPU acceleration, see [Enable GPU Acceleration for Indexes](/docs/how-to-guides/working-with-indexes/enable-gpu-indexes.mdx). #### Scaling You can set the number of replicas for your index in index settings. This is useful if you want to increase the availability of your index. ## Index Status The status is shown on the Indexes page and reflects the current state of file indexing for an index: - **Not indexed**: The pipeline is being deployed, but the files have not yet been indexed - **Indexing**: Your files are being indexed. You can see how many files have already been indexed if you hover your mouse over the _Indexing_ label. - **Indexed**: Your pipeline is deployed, all the files are indexed, and you can use your pipeline for search. - **Partially indexed**: At least one of the files wasn't indexed. This may be a problem with your file or a component in the pipeline. You can still run a search if at least some files were indexed. Check the index logs for details. - **Skipped**: All files were processed but none produced any documents. This happens when every file is skipped during indexing, for example, when files are duplicates or don't match the index's processing criteria. No documents are available for search. - **Failed to index**: All files failed during indexing. --- ## Language Models in Haystack Enterprise Platform # Language Models in is model agnostic and can load models directly from model providers, such as Hugging Face or OpenAI. You can use publicly available models but also your private ones if you connect with the model provider. *** ## Models in Your Pipelines You use models through pipeline components. There are a couple of pipeline components that use models. Have a look at this table for an overview of model applications and components that use them: | Model Type or Application | Component Using It | Description | | --- | --- | --- | | Large language models | `LLM`, `Agent`, Legacy components: `Generators`, including `ChatGenerators` | Use LLMs for various tasks. To use a regular model, use the `LLM` component. To use a model iteratively with tools, use the `Agent` component. You can use models from providers such as OpenAI, Cohere, Azure, and more, or models hosted on AWS SageMaker and Amazon Bedrock. You can also use your custom models that you can define on the Integrations page in Settings. | | Embedding models | Embedders | Embedders use embedding models to calculate vector representations for text and documents. There are two types of embedders: document embedders, used in indexing pipelines, and text embedders, used in query pipelines to embed the query. Both types of embedders should use the same embedding models. | | Question answering models | `ExtractiveReader` | The reader is used in extractive question answering. It highlights the answer in the document to pinpoint it and it uses transformer-based models to do that. | | Ranking models | Rankers | Rankers prioritize documents based on the criteria you specify, for example, a particular value in a document's metadata field. Model-based rankers use models to embed the documents and the query and thus build a strong semantic representation of the text. | To use a model, simply pass its name as a parameter to the component (it's usually the `model` parameter) or choose the model from the list on the component card. To use a proprietary model, [connect to the model provider](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx). takes care of loading the models. You can run models locally or remotely. Smaller models, like question answering or embedding models, are fast when run locally. Large models, like GPT-4, are faster to run remotely as they need optimized hardware. To run a model remotely, you may need to pass additional parameters in model kwargs. For detailed instructions, see the [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx) for the component that uses the model. When using LLMs with `LLM` or `Agent`, you can specify all additional model settings on the Advanced tab: This is the YAML configuration for the Agent's model settings: ```yaml components: agent: init_parameters: chat_generator: init_parameters: model: gpt-5.2 generation_kwargs: reasoning: effort: low verbosity: low type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator exit_conditions: - text max_agent_steps: 100 raise_on_tool_invocation_failure: false state_schema: documents: type: list[haystack.dataclasses.document.Document] _meta: used_by: local_search: output streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback ``` ## Recommended Models Larger models are generally more accurate at the cost of speed. If you don't know which model to start with, you can use one of the models we recommend. ### Large Language Models for RAG This table lists the models that we recommend for retrieval augmented generation (RAG) QA. You can use them with Generators in your pipelines. | Model URL | Description | Type | | :---------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | :---------- | | [Claude models by Anthropic](https://www.anthropic.com/product) | A transformer-based LLM that can be an alternative to the GPT models. It can generate natural language and assist with code and translations. | Proprietary | | [GPT models by OpenAI](https://platform.openai.com/docs/models/gpt-4) | Large multimodal models, suitable for most tasks. | Proprietary | For an overview of the models, see [Large Language Models Overview](/docs/learn/large-language-models-overview.mdx). ### Hosted LLMs ### Reader Models for Question Answering This table describes the models that we recommend for the question answering task. You can use them with your Readers. | Model URL | Description | Language | | :---------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------ | :----------- | | [deepset/roberta-base-squad2-distilled](https://huggingface.co/deepset/roberta-base-squad2-distilled) | A distilled model, relatively fast and with good performance. | English | | [deepset/roberta-large-squad2](https://huggingface.co/deepset/roberta-large-squad2) | A large model with good performance. Slower than the distilled one. | English | | [deepset/xlm-roberta-base-squad2](https://huggingface.co/deepset/xlm-roberta-base-squad2) | A base model with good speed and performance. | Multilingual | | [deepset/tinyroberta-squad2](https://huggingface.co/deepset/tinyroberta-squad2) | A very fast model. | English | You can also view state-of-the-art question answering models on the [Hugging Face leaderboard](https://huggingface.co/spaces/autoevaluate/leaderboards?dataset=squad_v2). ### Embedding Models This table describes the embedding models we recommend for calculating vector representations of text. You can use them with dedicated Embedders. | Model Provider | Model Name | Description | Language | | --- | --- | --- | --- | | Cohere | embed-english-v2.0 embed-english-light-v2.0 | See [Cohere documentation](https://docs.cohere.com/reference/embed). | English | | Cohere | embed-multilingual-v2.0 | See [Cohere documentation](https://docs.cohere.com/reference/embed). | Multilingual | | OpenAI | text-adda-002 | See [OpenAI documentation](https://openai.com/blog/new-and-improved-embedding-model). | English | | Sentence Transformers | [sentence-transformers/multi-qa-mpnet-base-do-v1](https://huggingface.co/sentence-transformers/multi-qa-mpnet-base-dot-v1) | Vector dimension\*: 768 | English | | Sentence Transformers | [intfloat/e5-base-v2](https://huggingface.co/intfloat/e5-base-v2) | Vector dimension\*: 768 | English | | Sentence Transformers | [intfloat/e5-large-v2](https://huggingface.co/intfloat/e5-large-v2) | Vector dimension\*: 1024 Slower than e5-base-v2 but performs better | English | | Sentence Transformers | [intfloat/multilingual-e5-base](https://huggingface.co/intfloat/multilingual-e5-base) | Vector dimension\*: 768 | Multilingual | | Sentence Transformers | [intfloat/multilingual-e5-large](https://huggingface.co/intfloat/multilingual-e5-large) | Vector dimension\* 1024 | Multilingual | *In language models, _vector dimension_ refers to the number of elements a vector representing a word contains, capturing its meaning and usage. The more dimensions, or numbers, in this vector, the more detail the model can understand about the word, though it also makes the model more complex to handle. It's best to try out different models and see what works best for your data. ### Ranker Models This table lists models to use with Rankers to rank documents. | Model | Description | Language | | :-------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- | :----------- | | [intfloat/simlm-msmarco-reranker](https://huggingface.co/intfloat/simlm-msmarco-reranker) | The best ranker model currently available. | English | | [cross-encoder/ms-marco-MiniLM-L-12-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-12-v2) | A slightly bigger and slower model. | English | | [cross-encoder/ms-marco-MiniLM-L-6-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2) | Slightly faster than ms-marco-MiniLM-L-12-v2 | English | | [svalabs/cross-electra-ms-marco-german-uncased](https://huggingface.co/svalabs/cross-electra-ms-marco-german-uncased) | In our practice, this is the best model for German. | German | | [jeffwan/mmarco-mMiniLMv2-L12-H384-v1](https://huggingface.co/jeffwan/mmarco-mMiniLMv2-L12-H384-v1) | A quite fast, multilingual model. | Multilingual | | [rerank-english-v2.0](https://docs.cohere.com/reference/rerank-1) | A Cohere model for English data. | English | | [rerank-multilingual-v2.0](https://docs.cohere.com/reference/rerank-1) | A Cohere model for multilingual data. | Multilingual | --- ## Model Context Protocol Learn what the Model Context Protocol (MCP) is, how it can improve your workflows, and how to use it in . *** ## What Is the Model Context Protocol? The Model Context Protocol (MCP) is a way to let AI systems, like large language models (LLMs), connect to the outside world. With MCP, AI can access the newest information, trigger actions, or interact with other systems. Instead of building a custom connection for every app, database, or API, MCP provides a universal way to do this. MCP acts like a universal adapter. It defines a common protocol, or a standard, for how AI applications communicate with external tools and data sources. Just as USB-C standardizes how devices connect, MCP standardizes how AI connects to external capabilities. For , this means you can connect pipelines to a wide range of tools and services with the same interface. MCP defines how an AI assistant requests data from tools and how those tools respond. When a tool supports MCP, you can use it across any compatible client, such as Cursor, Claude Desktop, or your own custom agent. ### Key Concepts MCP uses a client-server architecture with three key components: - MCP Host: The AI assistant the user interacts with, like Claude Desktop or VS Code. The host manages the overall workflow and launches one MCP client for each server it connects to. - MCP Client: The component that manages communication between the host and the server. It is usually part of the host application. - MCP Server: A program that offers capabilities, like tools, resources, or prompts, to the client or host. It can run locally or remotely. In , it is a workspace for which you create an MCP server with pipelines as tools. The host coordinates the entire process. It creates one MCP client to communicate with each MCP server. ### The Workflow Here's how a typical interaction works. Let's use the example of Claude Code as the host and a workspace as the MCP server: 1. The user asks Claude Code a question that requires an external tool, in this case a pipeline. 2. Claude Code forwards the query to its MCP client, which is its internal component. 3. The client starts a session with the workspace MCP server. 4. They exchange information about available tools and capabilities. 5. The client sends a tool call, the server returns the result, and the client passes the response back to Claude Code. 6. Claude Code then formats it into natural language for the user. ## Benefits of MCP - Vendor-agnostic integration: MCP handles the communication protocol, so you can focus on building rather than writing custom integration code. - Flexible tool access: Access a growing ecosystem of MCP-compatible tools, including database connections, web search capabilities, file system operations, API integrations, and custom business tools. - Enhanced AI capabilities: Give your AI models access to real-time data and tools, enabling them to answer questions with current information, perform actions on external systems, access specialized data sources, and execute complex workflows. - Future-proof architecture: As more tools adopt MCP, your pipelines automatically gain access to new capabilities without code changes. ## MCP in supports MCP in two main ways: by providing agents that can use external MCP servers and by providing a way to use pipelines as MCP tools. ### Using External MCP Servers You can connect your Agent components to external MCP servers to access third-party tools and data sources. This is useful when you need to integrate with services that provide MCP-compatible APIs. ### Using Pipelines as MCP Tools You can use your deployed pipelines as MCP tools, making them available to AI coding assistants like Cursor, VS Code, or Claude Code. In , this works at the workspace level: you create one MCP server for your workspace, then individually enable each pipeline as its tool. A pipeline is not available as a tool until you explicitly turn it on in the pipeline's settings. When an AI client connects to your workspace's MCP endpoint, it discovers all the pipelines you enabled and can call them as tools. Each tool can have its own name, description, and instructions to help the AI assistant understand when and how to use it. This means you can mix and match pipelines within a single MCP server — for example, a RAG pipeline for knowledge retrieval, a data processing pipeline for transformation tasks, and a summarization pipeline for document analysis — all accessible through one endpoint. #### Example Use Cases - Documentation assistant: Enable a RAG pipeline that searches your internal documentation - Code review helper: Use a pipeline that analyzes code patterns and suggests improvements - Data processing tool: Make data transformation pipelines available for development workflows - Knowledge search: Provide access to company knowledge bases through search pipelines For instructions on setting this up, see [Use Your Pipelines as MCP Tools](/docs/how-to-guides/productionizing-your-pipeline/expose-pipeline-as-mcp-tool.mdx). ## Related Information - [Use a Pipeline as an MCP Tool](/docs/how-to-guides/productionizing-your-pipeline/expose-pipeline-as-mcp-tool.mdx) - [Configure an Agent: Model, System Prompt, and Tools](/docs/configuring-agent) - [Agent Tools](/docs/agent-tools) - [Model Context Protocol Official Website](https://modelcontextprotocol.io/) --- ## Secrets and Integrations Add secrets and integration to safely connect to model and service providers. ## Overview Secrets and integrations let you connect to external models or services. These connections allow your pipeline components to use those services without including the API key directly in the component's configuration. ## Scope You can add secrets and integration at either the workspace or organization level: - Workspace-level connections are available only to pipelines and indexes within that specific workspace. - Organization-level connections are available to all workspaces in the organization. If the same provider is connected at both levels, the workspace-level connection takes priority and is used in pipelines and indexes. If you delete a workspace-level connection, but the same provider is connected at the organization level, the organization-level connection is used automatically. ## How Do They Work Each secret or integration sets an environment variable to store the API key. This way, pipeline components can access the key without you having to add it manually to the configuration. The API key is read from the environment variable. ## Integrations Integrations are most frequently used connections You can find them under Integrations in Workspace and Organization settings. To connect to a listed provider, just enter your API key and any required details. The platform fills in the integration name for you. ## Secrets Secrets let you connect to providers not listed on the Integrations page. Use them to: - Securely manage API keys required for custom components to authenticate without hard coding them in pipeline YAMLs. - Manage different API keys for development and production environments. You can create multiple secrets for one provider, such as one for a development key and another for a production key. This makes it possible to easily swap keys in the pipeline configuration. ### For Existing Components If you're using an existing component (like `LangfuseConnector`), check its documentation to learn the correct name for the secret. The component reads the API key from a specific environment variable, so the secret name must match that variable name. ### For Custom Components If you're building a custom component, make sure your code uses an environment variable to get the API key. Then, use that variable name as the secret name in the platform. --- ## User Roles and Permissions You can use a default role or create your own roles with custom permissions. # Role-Based Access Control (RBAC) offers role-based access control at two levels: organization and workspace. Roles are scoped at each level and define what users can access and manage, enabling precise control over assets. includes preset roles at both the organization and workspace levels. You can also define custom roles at the workspace level to set specific permissions. ## Preset Roles Preset roles are predefined roles you can assign to users. You can also use them as a starting point when creating custom roles. You can't edit preset roles. ### Organization Preset Roles The following preset roles grant permissions at the organization level: | Role | Scope | Permissions | |------|-------|-------------| | Admin | Organization | - Can perform tasks and manage users and workspaces at the organization level- Has write access to all workspaces in the organization- Can change roles of other organization members- Cannot change their own role- Can manage organization-wide assets, like secrets, integrations, API keys, custom model definitions, and more- Can view usage statistics- Can create custom roles- Can import custom components- Can view and manage MCP servers and tools| | Member | Organization | - Must be granted explicit access to workspaces to be able to perform tasks- Can view organization-wide assets, like secrets, integrations, and roles- Has no permissions on other organization-wide assets like usage statistics, custom components, or API keys | ### Workspace Preset Roles The following preset roles grant permissions at the workspace level: | Role | Scope | Permissions | |------|-------|-------------| | Editor| Workspace | - Has write access to all assets within a workspace, including secrets, integrations, API keys, custom model definitions, and more- Can manage workspace users- Can view and manage MCP servers and tools | | Search User | Workspace | - Can use Playground, including adding feedback and modifying query time parameters- Can use Jobs, including creating, running, and sharing- Can view MCP servers and tools | ## Custom Roles Organization and workspace Admins can create roles with custom permissions. Custom roles apply only at the workspace level. You can't create roles with organization-wide permissions.. ### Permissions When creating custom roles, you can either use a default role and its permissions as a starting point, or you can choose the permissions from scratch. The following table explains available permissions: Permission Access type Explanation Data Permissions Files No access The feature is hidden. Read-only - Can view a list of files in a workspace.- Can view file metadata.- Can view files.- Can download files.- Can see file references in generated answers. Read & write - Can upload, delete, and download files.- Can add and modify file metadata. Indexes No access The feature is hidden. Read-only - Can view all indexes in the workspace.- Can view index details on the Index Details page.- Can open an index in Pipeline Builder in view-only mode.- Can view names of indexed files.- Can export documents as CSV. Read & write - Can create, update, and delete indexes.- Can enable and disable indexes.- Can use index templates. Configuration Permissions Workspace statistics Read-only - Can view the homepage Pipelines No access The feature is hidden. Read-only - Can view pipelines on the Pipelines page.- Can view pipeline details on the Pipeline Details page.- Can open a pipeline in Pipeline Builder in view-only mode.- Can run searches in Playground and Prompt Explorer- Can activate pipelines Read & write - Can create, update, share, and delete pipelines.- Can configure pipeline service level.- Can deploy and undeploy pipelines.- Can duplicate pipelines.- Can use pipeline templates.- Can debug pipelines using the remote tunnel.- Can update prompts in the pipeline using Prompt Explorer Pipeline Templates No access The feature is hidden. Read-only - Can view templates and their details. Jobs No access The feature is hidden. Read-only - Can view jobs and job results on the Jobs page- Can download job results Read & write - Can create, run, share, view, update, and delete jobs Prompts No access The feature is hidden. Read-only - Can view and use custom prompts in the prompt hub in Prompt Explorer Read & write - Can create, update, and delete custom prompts in the prompt hub in Prompt Explorer Shared Prototypes No access The share option is inactive. Read-only - Can list active shared prototypes within a workspace using API Read & write - Can share pipeline prototypes.- Can update and delete shared prototypes. Feedback No access Feedback options are inactive. Read-only Can view feedback items. Read & write Can add, update, and view feedback. Feedback Management No access Feedback options are inactive. Read-only Can view feedback and feedback statistics, can export feedback across pipelines using API. Read & write - Can add, update, and delete feedback tags.- Can delete feedback items. Search history No access The feature is inactive. Read-only - Can view search history. Read & write - Can delete search history through API. API Keys Read & write - Create, configure, modify and delete API Keys in a workspace MCP Server No access The MCP tab in Workspace Settings and the MCP section in pipeline Settings are hidden. Read-only - Can view MCP server configuration in Workspace Settings.- Can view the MCP Tool section in pipeline Settings, but cannot make changes. Read & write - Can enable and configure the MCP server in Workspace Settings.- Can enable and configure MCP tools in pipeline Settings. Models No access to custom model definitions Custom model definitions are not visible in the workspace. Read-only - Can view workspace custom model definitions. Read & write - Can create, update, and delete workspace custom model definitions. Secrets & Integrations Read-only - Can view secrets and integrations of a workspace Read & write - Can add and delete secrets- Can connect and disconnect to an integration Tool Registry No access The feature is hidden. Read-only - Can view tools in the workspace tool registry.- Can view tool details, including MCP server and pipeline tool configuration. Read & write - Can create, update, and delete tools in the workspace tool registry.- Can register MCP server tools and pipeline tools for use in agents. # Examples ## Prompt Engineer To create a custom Prompt Engineer role that: - Can create, update, save, and delete prompts - Can test prompts in Prompt Explorer - Can view file references in generated answers - Can add feedback to generated answers - Cannot update prompts in pipelines You would need the following permissions: | Asset | Access Type | | :-------- | :----------- | | Pipelines | Read | | Files | Read | | Prompts | Read & write | | Feedback | Read & write | --- ## Basic Concepts That's the place where you can check the meaning of terms and notions used in . *** ## Component Components are building blocks of pipelines. Each component performs a specific task in a pipeline. For example, PromptBuilder is a component that inserts variables and documents into a prompt and sends it to the Generator component that uses an LLM to perform the instructions from the prompt. Components in a pipeline act like building blocks that you can mix and match or replace. For a list of available components, see [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). ## Document Refers to an individual piece of text stored in the document store. Multiple documents may originally come from one file. Documents are created during indexing, when the files are preprocessed, cleaned, split, and converted into passages of text. Pipelines use documents at search time. They don't work on files stored in , but retrieve documents from the document store and run searches and other tasks on them. ## Document Store A database that stores the text documents, their metadata, and (optionally) embeddings. At search time, Retrievers in your pipeline search the document store to find documents that are the most relevant to the query. To check the databases supports, see [Document Stores](/docs/concepts/document-stores/document-stores.mdx). ## File Refers to the raw file you upload to (for example, a PDF). When an indexing pipeline runs, files get converted, cleaned, and split into _documents_, which contain the actual text and are then used by pipelines for finding the best answer to a query. ## Index An index defines how your files are preprocessed, converted into searchable documents, and written into a document store. Indexes are reusable among query pipelines. ## Indexing It refers to a process of preprocessing your files, turning them into documents, and then storing those documents in the document store. Indexing happens after you deploy a pipeline. The exact indexing steps are defined in the indexing pipeline (for example, the size of the documents resulting from a file). ## Organization In , your company is assigned an organization. Within each organization, there are up to 100 workspaces. When you invite users to , they gain access to your organization and all the workspaces within it. ## Pipeline In you work with pipelines. A pipeline is an app that defines the flow of data. Pipelines define the steps that happen after the user asks a query until they get an answer. Pipelines are made up of components that define the processing steps. Components in pipelines are connected by their input and output, so that the output of one component is compatible with the input of another one. You can mix and match the components in a pipeline. ## Workspace In , you work in workspaces, where you upload your data and create and maintain your pipelines. Data and pipelines are not shared across workspaces. All workspaces belong to an organization. When you invite people to your organization, they automatically receive access to all workspaces within this organization. You cannot limit access to a workspace. --- ## Haystack Enterprise Platform Status # Status Visit the [ status page](https://status.deepset.ai/) to: - Check the general availability of the . - Monitor the status of your deployed pipelines, with separate views for deployments in the EU and US regions. The status page is directly connected to our monitoring system. It automatically updates to reflect the current state of the platform and your pipelines, so you always have access to the latest information. Each bar represents the status on a particular day. Hover over a day to check the details: --- ## Using deepset MCP Server The deepset-mcp package contains an official MCP server and a Python SDK. Use the MCP server with your agents to interact with pipelines. Use the SDK to programmatically access resources. *** You can find the MCP server and SDK in the [deepset-mcp GitHub repository](https://github.com/deepset-ai/deepset-mcp-server). For detailed documentation, see the [deepset-mcp documentation](https://deepset-ai.github.io/deepset-mcp-server/). --- ## Quick Start Guide Create an AI-powered pipeline using one of our ready-made templates and enjoy the benefits of . *** In a nutshell, here are the steps to create a search app: 1. Upload your data to the Platform or connect your data source. 2. Create an index to prepare your data for search and write it to a database (document store). 3. Create a pipeline to build your search application and connect it to the index. 4. Test your pipeline and share your prototype with others. Gather feedback and iterate. 5. Deploy your pipeline to production. ## Set Up Your Workspace In , you work in workspaces, where you store your files, indexes, and pipelines. You can have up to 100 workspaces in your organization. Let's start by creating a workspace dedicated for your data: 1. Log in to . You land in the `default` workspace. 2. In the upper left corner, click the name of the workspace. This opens a list of workspaces 3. Type the name of the new workspace and click **Create**. You can switch between workspaces by clicking the name of the workspace and choosing another workspace from the list. ## Upload Your Files :::tip 📂 Sample files You can also use one of the sample datasets we prepared. They're available on the Files page. ::: Add the files on which you want to run your searches: 1. Make sure you're in the workspace you just created, and in the left navigation, go to _Files > Upload Files_. 2. Drag the files from your computer and drop them into the Upload Files window. 3. Click **Upload**. Your files are now listed on the Files page. :::tip Other upload options You can also use SDK or REST API endpoints. For details, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). ::: ## Create an Index Indexes define how your files are prepared for search and specify the document store where they’re saved. For an easy start, use a template: 1. Go to **Indexes** and click **Create Index**. 2. Choose the _Standard Index (English)_ template. This template works for most use cases. 3. Click the template card, give your index a name, and click **Create Index**. 4. Click More actions next to your index and choose **Enable**. Your files are being indexed. Once the indexing is complete, your query pipeline can run searches on the indexed files. :::tip Indexes You can reuse indexes among your query pipelines. To learn more about indexes, see [Indexes](/docs/concepts/indexes/indexes.mdx). ::: ## Create a Pipeline Pipelines in are the engines powering your apps. A pipeline defines the steps your app takes to resolve a user query. Now, create a pipeline in the simplest way: 1. In , go to **Pipeline Templates**. 2. Find a template that best matches your use case, hover over it, and click **Use Template**. 3. Give your pipeline a name and click **Create Pipeline**. You're redirected to the Builder. 4. Find the `OpenSearchDocumentStore` component and click it to open its configuration. This component is an interface to the document store where your indexed files are stored. By default, it's configured to use the index you previously created. Available indexes are shown in the list on the component card. 5. Save your pipeline. 6. To test your pipeline, click **Run Pipeline** next to the `Input` component. 6. To test your pipeline in the Playground or share it with others, deploy it first. Click **Deploy** in the upper right corner. :::tip More about pipelines For a deeper dive into pipelines and components, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). ::: ## Test Your Pipeline 1. In Builder, switch to **Playground**. 2. Choose the pipeline version to test. 3. Type a query and click **Submit** to try out your pipeline. That's it! ## What To Do Next? Have a look at our tutorials, we suggest you start with the basic ones available at [Learn the Basics](/docs/tutorials/learn-the-basics/tutorial-building-a-robust-rag-system.mdx). For guides on how to perform tasks in , see the _How-to Guides_ section. To learn about how things work in and understand the concepts, see the _Concepts_ section. --- ## Third-Party Software This is where you can find the licensing information for third-party software used in . *** ## Boring SSL uses BoringSSL, which is under the [OpenSSL SSLeay license](https://www.openssl.org/source/license-openssl-ssleay.txt). This product includes cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)). This product includes software written by Tim Hudson ([tjh@cryptsoft.com](mailto:tjh@cryptsoft.com)). The source code can be found [here](https://github.com/google/boringssl). ## elkjs uses elkjs, which is published under the [EPL 2.0 License](https://github.com/kieler/elkjs/blob/master/LICENSE.md). It improves the visual layout of graphs. This library takes the layout-relevant part of ELK and makes it available to JavaScript. [The Eclipse Layout Kernel ](https://www.eclipse.org/elk/)(ELK) implements an infrastructure to connect diagram editors or viewers to automatic layout algorithms. You can find the source code of the project in the [Github elkjs repo](https://github.com/kieler/elkjs). --- ## Managing Organization Settings Invite members, add workspaces, create organization-level integrations, secrets, and API keys. # About This Task All settings you configure on the Organization Settings page apply across the entire organization, including all its workspaces. For example, if you add an integration here, it becomes available to every workspace in the organization. # Access Organization Settings 1. Click your profile icon and choose _Settings_. 2. Go to **Organization**. 3. Switch between tabs to access the settings you want to update. You can invite users to organization, assign them roles for each workspace, add secrets, integrations, and API keys that apply organization-wide. --- ## Managing Workspace Settings You can have up to 100 workspaces in your organization, each with separate data. You can choose which users can access each workspace. # About This Task In , you work within workspaces. Each workspace has its own data, pipelines, indexes, and jobs which aren't shared with other workspaces. Members, integrations, secrets, and API keys in the Workspace Settings apply only to this workspace. For example, if you add an integration here, it will work only within this workspace. The same goes for secrets and API keys. # Create Workspaces When you create a workspace, only Admins have access by default. To allow others to access your workspace, you must add them to your organization and assign roles. 1. In , click the workspace name in the upper left corner. 2. Enter the workspace name and click **Create**. You're automatically redirected to the new workspace. # Manage Workspace Settings To check the current workspace ID, integrations, secrets, and API-keys, perform these steps: 1. Click your profile icon and choose _Settings_. 2. Go to **Workspace**. 3. Switch between tabs to adjust settings. --- ## Updating Settings Enable experimental features, manage organization and workspace settings. # About This Task You can manage members, integrations, secrets, and API keys at the workspace and organization levels. The settings you modify on the Workspace Settings page apply only to this workspace, not to the whole organization. The same goes for the settings you update on the Organization Settings page. If you add integrations or secrets for an organization, all the workspaces in this organization will be able to use them. But if you add integrations or secrets for a workspace, only this workspace will be able to use them. If you delete a secret or an integration from a workspace but an identical organization-level secret or integration exists, it will be used instead. You can also use settings to enable and test experimental features. # Update Settings - [Managing Organization Settings](/docs/getting-started/update-settings/managing-organization-settings.mdx) - [Managing Workspace Settings](/docs/getting-started/update-settings/managing-workspace-settings.mdx) --- ## Using Haystack Enterprise Documentation with AI # Using Documentation with AI Connect your AI assistant to search and retrieve information from documentation using the MCP server. You can also copy and export single pages in Markdown format to use them in your AI assistant. *** ## Use the Documentation MCP Server The documentation is available as a Model Context Protocol (MCP) server that you can connect to your AI assistant to search this documentation directly. The MCP server is free to use and requires no authentication. ### Server URL The documentation MCP server is available at: ``` https://docs.cloud.deepset.ai/api/mcp ``` ### Server Tools The MCP server comes with two tools: - `search_docs`: Search the documentation. - `list_doc_sections`: List all main documentation sections. ### Connect to Cursor Add this code to your Cursor MCP settings (.cursor/mcp.json) in your project or global settings: ```json { "mcpServers": { "deepset-docs": { "url": "https://docs.cloud.deepset.ai/api/mcp" } } } ``` ### Connect to Claude Desktop Add this code to your Claude Desktop configuration (*~/Library/Application Support/Claude/claude_desktop_config.json* on macOS or %APPDATA%\Claude\ on Windows): ```json { "mcpServers": { "deepset-docs": { "url": "https://docs.cloud.deepset.ai/api/mcp" } } } ``` ### Connect to VS Code Add this code to your VS Code settings (.vscode/mcp.json): ```json { "mcpServers": { "deepset-docs": { "url": "https://docs.cloud.deepset.ai/api/mcp" } } } ``` ## Copy Single Pages You can also copy a page as Markdown that LLMs can easily read. Use the **Copy** button in the top right corner of a page. Expand the button to view additional options. --- ## Haystack Enterprise Platform and Haystack # and Haystack Open Source Haystack is 's open source Python framework for creating production-ready AI-based systems. It's also the underlying technology for . *** uses the same components, pipelines, and data classes as the Haystack open source framework. Let's explain what this means and how you can use it in your day-to-day work. If you're not familiar with the open source version of Haystack, check the following resources: - [Haystack website](https://haystack.deepset.ai/) - [Haystack documentation](https://docs.haystack.deepset.ai/docs/intro) - [Haystack GitHub repository](https://github.com/deepset-ai/haystack/tree/main) We bump Haystack version used in with every Haystack release, so that it's always up to date. ## Pipelines uses Haystack pipelines, giving you the full flexibility of Haystack features, including loops and multiple branches in your workflows. ### Pipelines Start and End Initial and final components: The components you can use at the start and end of indexes and query pipelines are restricted: - Indexes must start with `FilesInput`, which acts as a placeholder for the files you upload to . There are no restrictions on the final component, though it is typically `DocumentWriter`. - Query pipelines must start with `Input` and end with `Output`. For more information, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). ## Components combines open source Haystack components with its own unique components. Components specific to have names that start with `Deepset`. We introduced these custom components to support features tailored specifically for . Some components may appear to be duplicates, for example `AnswerBuilder` and `DeepsetAnswerBuilder`. Typically, these "duplicates" extend the original component by adding functionality needed for . For instance, we created `DeepsetAnswerBuilder` to ensure document references display correctly in 's interface. This is enabled by an additional parameter, `reference_pattern`, which you can configure in `DeepsetAnswerBuilder`. The list of components is constantly growing giving you more possibilities. Additionally, you can create your own custom components. For more information, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx). ## Data Classes uses Haystack's objects, or data classes namely: - `Answer`, including `ExtractedAnswer` and `GeneratedAnswer` - `ByteStream` - `ChatMessage` - `Document` - `StreamingChunk` - `ImageContent` Each of these objects has properties you can access. For detailed description of the data classes and their properties, see [Haystack's Data Classes](https://docs.haystack.deepset.ai/docs/data-classes). ### Data Classes in Jinja2 Templates It's useful to know the objects you can use and their attributes when working with components that use Jinja2 templates: `PromptBuilder`, `OutputAdapter`, and `ConditionalRouter`. You can access an object's attribute in the template, for example: ```jinja2 {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} ``` This expression iterates through all documents to fetch their content. This is achieved by accessing the `content` attribute of the `document` data class using `document.content`. You can also use the `document`'s `meta` attribute to work with metadata. The syntax for this is: `document.meta.metadata_key`. For more examples, see [Use Metadata in Your Search System](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx). The same approach applies to other data classes and their attributes. ### Data Classes as Output and Input Variables Additionally, certain components use or output data classes, for example `AnswerBuilders` output a list of `GeneratedAnswer` objects, or `Rankers` accept a list of `document` objects. It's good to be aware of that when connecting components to make sure the connections are compatible. You can check the details on each component documentation page. For details, see [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). # Haystack Experimental Features The `haystack-experimental` package offers experimental features you can try out. You can find it on [GitHub](https://github.com/deepset-ai/haystack-experimental). For more information, check the [Haystack documentation](https://github.com/deepset-ai/haystack-experimental). Components in the `haystack-experimental` package are not included in the Pipeline Builder's component library by default. You can add them as custom components, but keep in mind that experimental features are not intended for production pipelines. They're likely to change or be deprecated. For details, see [Custom Components Using Haystack Experimental](/docs/concepts/about-pipelines/custom-components.mdx#components-using-haystack-experimental-features) features. --- ## Feature List is an end-to-end platform for building, deploying, and managing AI applications in production. From RAG systems to AI agents, it gives you full control over every layer of the stack while handling the infrastructure complexity for you. *** ## AI Agents Build autonomous, multi-step AI systems that reason, plan, and act. The Agent uses an LLM to decide which tools to call and loops until it reaches a result, handling tasks far beyond simple question answering. Our agents are: - Model-agnostic: Use any LLM as the Agent's brain and easily swap them out. - Rich tool ecosystem: Give your Agent access to pipelines, custom Python functions, and MCP servers as tools. - Controllable: Define exit conditions so the Agent stops exactly when and how you want. - Context-aware: Built-in conversation memory tracks history and tool usage across turns. - Real-time streaming: Stream Agent responses as they're generated. - Full observability: Trace every Agent decision with Langfuse or Weights & Biases Weave. Start with ready-made Agent templates and customize from there. For details, see [AI Agents](/docs/concepts/ai-agents/ai-agent.mdx) and [Building AI Agents](/docs/how-to-guides/building-agents/building-ai-agents.mdx). ## Visual Pipeline Builder Design AI applications visually with Pipeline Builder, an intuitive drag-and-drop editor. - Drag and drop from a library of 180+ pre-built components to assemble your pipeline. - Switch between visual editing and YAML with real-time synchronization. - Build complex flows with branching, loops, and conditional routing. - Export to YAML or Python for local development and version control. - Jump-start with curated, tested pipeline templates covering RAG, agents, data processing, and more. - Inspect and fix all validation and runtime issues in one place. To learn more, see [Create a Pipeline in Studio](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). To understand pipelines, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) ## Model Flexibility Avoid vendor lock-in. is model-agnostic, so you can swap LLMs, embedding and ranking models without changing your pipeline architecture. Supported providers include OpenAI, Anthropic, Azure OpenAI, Amazon Bedrock, Google Gemini, Cohere, Mistral, NVIDIA, Meta Llama, Together AI, and more. For the full list, see [Supported Connections and Integrations](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). ## Multimodal AI Build systems that go beyond text. Process, understand, and generate content across multiple data types, including audio, images, and documents: - Audio: Transcribe speech to text with components like Whisper and build search over audio content. - Images: Use multimodal LLMs (GPT-4o, Claude, Gemini, and others) to analyze and reason over images. - Documents: Extract structured data from PDFs, Office files, and scanned documents using Azure Document Intelligence, Unstructured.io, or Docling. For more details, see [Multimodal Systems](/docs/concepts/about-pipelines/multimodal-systems.mdx). ## MCP Support Connect your AI applications to external systems through the Model Context Protocol (MCP). Use the official [deepset MCP server](https://github.com/deepset-ai/deepset-mcp-server) to expose pipelines as tools for any MCP-compatible agent, or connect your agents to third-party MCP servers. For details, see [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx) and [Model Context Protocol](/docs/concepts/model-context-protocol.mdx). ## Data Ingestion and Processing Bring in data from any source and prepare it for your AI applications: - File processing: Handle PDFs, Office documents, HTML, images, and audio with out-of-the-box converters and preprocessors. For details, see [Preparing Your Data](/docs/how-to-guides/working-with-indexes/prepare-your-data.mdx). - External services: Process files with Azure Document Intelligence, Unstructured.io, or DeepL for translation. - Metadata: Attach, filter, and use metadata throughout your pipelines. ## Flexible Document Stores Choose where your data lives. supports multiple document stores so you can use the vector database that fits your stack: - **Managed**: OpenSearch (fully managed by ). - **Bring your own**: Elasticsearch, MongoDB Atlas, Pinecone, Qdrant, Weaviate, PGVector. - **Databases**: Connect to Snowflake for structured data queries. You can also bring your own S3 bucket or OpenSearch cluster through [VPC integration](/docs/how-to-guides/working-with-your-data/setting-up-your-vpc/connect-your-own-file-storage.mdx). For an overview, see [Document Stores](/docs/concepts/document-stores/document-stores.mdx). ## Custom Components Extend the platform with your own logic. Write custom Python components and use them alongside built-in ones in your pipelines. - Create reusable, versioned components shared across your organization. - Use the inline Code component for quick, single-pipeline customizations. - Securely manage API keys with secrets—no credentials in code. For details, see [Add Custom Code](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/add-custom-code.mdx). ## Prompt Engineering Iterate on prompts faster with built-in tools: - Test and refine prompts in Prompt Explorer with live pipeline responses. - Compare prompt performance side by side across up to three pipelines. - Save prompts to a library and update them across pipelines without redeployment. For details, see [Engineering Prompts](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). ## Production-Grade Infrastructure Deploy with confidence. handles scaling, reliability, and performance so you can focus on your application. - One-click deployment Move from prototype to production in seconds. - Autoscaling: Pipelines scale automatically with traffic (up to ten replicas for production workloads). You can configure replicas and standby behavior in the pipeline's **Settings** tab. - Service levels: Mark pipelines as Development or Production to control standby behavior and resource allocation. For details, see [Pipeline Service Levels](/docs/concepts/about-pipelines/about-pipelines.mdx). - CI/CD: Automate pipeline deployment with [GitHub Actions](/docs/how-to-guides/productionizing-your-pipeline/implement-cicd-with-github-actions.mdx). ## Observability and Tracing Understand exactly what happens inside your AI applications: - Pipeline logs: View component-level logs with timestamps, messages, and log levels. - Live debugger: Inspect component behavior in real time from Pipeline Builder. - Langfuse integration: Trace full query journeys with spans, latency breakdowns, and dependency maps. For details, see [Trace with Langfuse](/docs/how-to-guides/productionizing-your-pipeline/trace-with-langfuse.mdx). - Weights & Biases Weave: Monitor ML telemetry, token counts, and performance metrics. For details, see [Use Weights & Biases](/docs/how-to-guides/productionizing-your-pipeline/use-weights-and-biases.mdx). - Remote debugging: Connect to running pipelines through a VS Code tunnel. For more information on observability, see [Trace Your Pipelines](/docs/how-to-guides/productionizing-your-pipeline/trace-your-pipelines.mdx). ## User Feedback Test your AI applications with real users and improve continuously: - Shareable prototypes: Generate branded, shareable links to your pipeline—no login required for testers. Customize with your logo and colors. FOr more information, see [Share a Pipeline Prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). - Structured feedback: Collect ratings, tags, and comments from users. Group, filter, and export feedback for analysis. For details, check [Collect User Feedback](/docs/how-to-guides/evaluating-your-pipeline/collect-feedback.mdx). - Playground: Test pipeline responses interactively before sharing. For instructions how to do it, see [Testing Your Pipeline](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). ## Batch Processing with Jobs Run queries at scale using [Jobs](/docs/concepts/about-jobs.mdx): - Process query sets in bulk across your entire dataset. - Run queries once on all files or repeat per individual file. - Share formatted results with anyone—no login required. ## Enterprise Security and Access Control Keep your data and applications secure with enterprise-grade access management: - Role-based access control: Assign preset or custom roles with granular permissions at the organization and workspace levels. For details, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). - Single sign-on (SSO): Authenticate through your identity provider. For details, see [Enable SSO](/docs/how-to-guides/managing-access/enable-single-sign-on-sso.mdx). - Secrets management: Store API keys and credentials securely, scoped to workspaces or organizations. To learn about secrets, see [Secrets and Integrations](/docs/concepts/secrets-and-integrations.mdx). - VPC integration: Run with your own OpenSearch cluster and S3 bucket for full data isolation. For details, see [Connect Your Own File Storage](/docs/how-to-guides/working-with-your-data/setting-up-your-vpc/connect-your-own-file-storage.mdx). - Workspace isolation: Organize teams and projects into isolated workspaces (up to 100 per organization). ## REST API and SDK Integrate into your applications and workflows: - REST API: Full programmatic access to pipelines, files, indexes, jobs, and feedback. For full reference, see [API](/docs/api/index.mdx). - Python SDK: Upload files, manage pipelines, and automate workflows with Python or the CLI. To learn more, see [Working with the SDK](/docs/how-to-guides/working-with-the-sdk/working-with-the-sdk.mdx). - MCP server Expose pipelines as tools for any MCP-compatible agent. For licensing information about third-party software used in , see [Third Party Software](../third-party-software.mdx). --- ## What's Haystack Enterprise Platform? # What's ? is a platform for building production-ready AI-powered applications and managing them across the full lifecycle — from prototyping to large-scale production. You get everything you need to work with your data, choose your models, build and evaluate, share prototypes with users, and run and monitor your apps in production. *** ## Upload and Index Your Data Upload your files and index them so they are ready for use in your AI apps. provides components that handle many file types out of the box, including converters and preprocessors for PDFs, Office documents, images, and more. Use components such as OCR and document conversion to turn your raw data into searchable content. Configure an [index](/docs/concepts/indexes/indexes.mdx) once, and your data is cleaned, chunked, and stored in a document store for fast retrieval by your pipelines. ## Build Enterprise-Ready Agents and Advanced RAG Apps Build [AI agents](/docs/concepts/ai-agents/ai-agent.mdx) that reason, use tools, and complete multi-step tasks, or design advanced [RAG (retrieval-augmented generation)](/docs/tutorials/learn-the-basics/tutorial-building-a-robust-rag-system.mdx) pipelines that ground answers in your documents. You work with [pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) made of components — retrievers, rankers, generators, and more — that you can mix and match in the visual [Pipeline Builder](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). Switch components or models anytime to improve results. ## Integrate with Model Providers and Observability Services is model-agnostic: you can use multiple LLM and embedding providers in the same app and switch models when you need to. Integrate with tracing and observability services such as [Langfuse](https://langfuse.com) and Weights & Biases Weave so you can trace pipeline runs, debug issues, and improve performance. For more, see [Trace Your Pipelines](/docs/how-to-guides/productionizing-your-pipeline/trace-your-pipelines.mdx). ## Share Prototypes Before Going to Production Get feedback early by sharing your pipeline with colleagues and end users. Share a link to a pipeline prototype that you can customize with your logo and brand colors. Recipients can try it and give feedback without logging in or creating accounts. Collect feedback, improve your app, and once it's ready, bring it to production using the REST API. ## Use the Powerful REST API Control and integrate from your own applications using the [REST API](/docs/api/index.mdx). Run queries, manage files and indexes, and automate workflows. The API is resource-oriented and uses standard HTTP verbs and JSON responses. ## Monitor with Built-in Logs and App Performance Dashboard Use built-in [monitoring and logs](/docs/how-to-guides/productionizing-your-pipeline/pipeline-performance.mdx) to see what your pipelines are doing and how they perform. View pipeline logs on the Pipeline Details page, track request volume and response times, and understand user behavior. Combine this with tracing integrations for full visibility from development to production. To get started, check [Basic Concepts](/docs/getting-started/basic-concepts.mdx) for core terms, or follow the [5-Step Guide to Building a Successful Prototype](/docs/learn/5-step-guide-to-building-a-successful-prototype.mdx) from use case to testing. --- ## Haystack Enterprise Platform 2.0 # 2.0 Welcome to v2.0! We've introduced many new features designed to enhance your experience with greater flexibility and new possibilities. *** ## What Changed The new release comes with significant changes in how pipelines and components work bringing you more freedom and flexibility when building your apps. With this update, you'll find: - New components that replace pipeline nodes to expand your capabilities. - Enhanced connections within pipelines for streamlined workflows, including loops and multiple branches. - Clear validation and meaningful error messages. ## Pipelines Pipelines in version 2.0 are much more flexible. You can use them to create sophisticated loops that cycle back to a component, branch out, loop back and retry, allowing for the integration of complex AI tasks. Components remain the building blocks of pipelines. Read more in [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). Version 2.0 also introduces changes to the YAML configuration file, including new formatting, component connections, and explicit pipeline inputs and outputs definitions. ## Nodes Pipeline nodes in 2.0 are called _components_. Components are the core elements of pipelines. In new pipelines, you explicitly define how components connect and which outputs they send or receive. For details on how specific components work, see [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). This table summarizes the components that replace nodes from the previous version: | Version 1.0 | Description | Version 2.0 | | ----------- | ----------- | ----------- | | `AnswerDeduplication` | Used in extractive QA pipelines to ensure there are no overlapping answers from the same document. | Not available, this functionality is built into `ExtractiveReader`, so no additional component is needed. | | `Converters` | Convert files to documents. There are various converters available for different file types. | `Converters` | | `DeepsetCloudDocumentStore` | A database for storing documents the pipeline can access at search time. | `OpenSearchDocumentStore` | | `EntityExtractor` | Extracts predefined entities out of the text. | `NamedEntityExtractor` | | `FileDownloader` | Download source files and stores them locally. | `S3Downloader` | | `FileTypeClassifer` | Routes files to appropriate pipeline branches based on their type. | `FileTypeRouter` | | `JoinAnswers` | Joins answers from different components into a single list of answers. | `AnswerJoiner` | | `JoinDocuments` | Joins documents from different components into a single list. | `DocumentJoiner` | | `PreProcessor` | Cleans and splits documents before writing them into the document store. | `PreProcessors`: v2.0 adds a number of preprocessors, each performing a separate task, like cleaning or splitting documents. | | `PromptNode` | Uses an LLM of your choice in the pipeline. | `PromptBuilder`, `ChatPromptBuilder` and `Generators`. v2.0 introduces `PromptBuilder` and `ChatPromptBuilder` that renders the prompt you can then send to a generator. | | `QueryClassifier` | Categorizes queries into keyword-based and natural language queries. | `TransformersZeroShotTextRouter` and `TransformersTextRouter` | | `RetrievalScoreAdjuster` | Adjusts document scores assigned by a retriever or a ranker. | This is now handled by `TransformersSimilarityRanker` through the `calibration_factor` and `score_threshold` parameters. | | `Ranker` | Ranks documents based on specific criteria, such as their similarity to the query. | `Rankers` | | `Reader` | Locates and highlights answers in documents. | `ExtractiveReader` | | `ReferencePredictor` | Predicts references for the generated answer. | LLM-generated references. | | `Retriever` | Retrieves documents from the document store based on their relevance to the query. | `Retrievers` | | `Shaper` | Modifies the input and output types. | `OutputAdapter` | ## Filters Version v2.0 changes the syntax of filters towards a more Python-oriented approach with logical operators explicitly defined. The filter syntax used in v1.0 will continue to be supported. For details on how to construct filters in v2.0, see [Filtering Logic](/docs/how-to-guides/working-with-your-data/working-with-metadata/filtering-logic.mdx). --- ## Release 2024.11 November brings new document stores, support for more models, optional indexing pipelines and more. Read on to find out! *** ## More Document Stores Document store is where your query pipelines access data. The indexing pipeline converts your files into documents and stores them in a document store of your choice. Until now, Deepset Cloud has supported the OpenSearch document store, but the list has grown. Starting with this release, you can use: - [Elasticsearch](https://www.elastic.co/elasticsearch) - [Pinecone](https://www.pinecone.io/) - [Qdrant](https://try.qdrant.tech/high-performance-vector-search?utm_source=google&utm_medium=cpc&utm_campaign=21518712216&utm_content=163351119977&utm_term=qdrant&hsa_acc=6907203950&hsa_cam=21518712216&hsa_grp=163351119977&hsa_ad=707722911583&hsa_src=g&hsa_tgt=kwd-1329481093586&hsa_kw=qdrant&hsa_mt=e&hsa_net=adwords&hsa_ver=3&gad_source=1&gclid=Cj0KCQiAlsy5BhDeARIsABRc6Zuj6VlE9jQcBILRmdOLM7wh4nYZHo0me1DEcEpTU_m5zvg50wRanQUaAn72EALw_wcB) - [Weaviate](https://weaviate.io/platform) Each document store comes with dedicated Retrievers to make retrieval make the best use of the document store's technology. Check [Document Stores](/docs/concepts/document-stores/document-stores.mdx) for more details. ## Sample Datasets Want to try a pipeline quickly but have no data? Use the sample files we prepared on healthcare, law, and tech and finance. They're available on the Files page: ## Export Your Pipelines as Python Save your pipelines locally as Python files. Pipelines that include deepset Cloud custom components (like our templates) may need additional adjustments and won't work out of the box after export. Export is available in Pipeline Builder - open any pipeline for editing and you'll find it there. ## Support For More Models and Integrations :::tip Secrets Create secrets to securely manage connections to model providers or integrations. For more information, see [Add Secrets to Connect to Third Party Providers]. ::: We've added support for the following model providers: - **Fastembed**: Models for generating embeddings and ranking documents. We've added the following components through which you can use Fastembed models: - Embedders: - [FastembedTextEmbedder](/docs/reference/pipeline-components/legacy-components/FastembedTextEmbedder.mdx) - [FastembedDocumentEmbedder](/docs/reference/pipeline-components/legacy-components/FastembedDocumentEmbedder.mdx) - [FastembedSparseTextEmbedder](/docs/reference/pipeline-components/legacy-components/FastembedSparseTextEmbedder.mdx) - [FastembedSparseDocumentEmbedder](/docs/reference/pipeline-components/legacy-components/FastembedSparseDocumentEmbedder.mdx) - Rankers: - [FastembedRanker](/docs/reference/pipeline-components/legacy-components/FastembedRanker.mdx) - **Google Vertex AI** available through the following Generators: - [VertexAIImageQA](/docs/reference/pipeline-components/integrations/google-vertex/VertexAIImageQA.mdx) - [VertexAICodeGenerator](/docs/reference/pipeline-components/integrations/google-vertex/VertexAICodeGenerator.mdx) - [VertexAITextGenerator](/docs/reference/pipeline-components/integrations/google-vertex/VertexAITextGenerator.mdx) - [VertexAIImageCaptioner](/docs/reference/pipeline-components/integrations/google-vertex/VertexAIImageCaptioner.mdx) - [VertexAIImageGenerator](/docs/reference/pipeline-components/integrations/google-vertex/VertexAIImageGenerator.mdx) - [VertexAIGeminiGenerator](/docs/reference/pipeline-components/integrations/google-vertex/VertexAIGeminiGenerator.mdx) - [VertexAIGeminiChatGenerator](/docs/reference/pipeline-components/integrations/google-vertex/VertexAIGeminiChatGenerator.mdx) - **Jina AI** embedding and ranking models available through: - Embedders: - [JinaTextEmbedder](/docs/reference/pipeline-components/integrations/jina/JinaTextEmbedder.mdx) - [JinaDocumentEmbedder](/docs/reference/pipeline-components/integrations/jina/JinaDocumentEmbedder.mdx) - Rankers: - [JinaRanker](/docs/reference/pipeline-components/integrations/jina/JinaRanker.mdx) - **Llama.cpp** library for efficient inference of large language models, available through: - Generators: - [LlamaCppGenerator](/docs/reference/pipeline-components/legacy-components/LlamaCppGenerator.mdx) - [LlamaCppChatGenerator](/docs/reference/pipeline-components/legacy-components/LlamaCppChatGenerator.mdx) - **Mistral AI** models available through an API with a pay-as-you-go access to the latest Mistral models. You can use it through: - Embedders: - [MistralTextEmbedder](/docs/reference/pipeline-components/integrations/mistral/MistralTextEmbedder.mdx) - [MistralDocumentEmbedder](/docs/reference/pipeline-components/integrations/mistral/MistralDocumentEmbedder.mdx) - Generators: - [MistralChatGenerator](/docs/reference/pipeline-components/integrations/mistral/MistralChatGenerator.mdx) - **Ollama** models available through: - Embedders: - [OllamaTextEmbedder](/docs/reference/pipeline-components/legacy-components/OllamaTextEmbedder.mdx) - [OllamaDocumentEmbedder](/docs/reference/pipeline-components/legacy-components/OllamaDocumentEmbedder.mdx) - Generators: - [OllamaGenerator](/docs/reference/pipeline-components/legacy-components/OllamaGenerator.mdx) - [OllamaChatGenerator](/docs/reference/pipeline-components/legacy-components/OllamaChatGenerator.mdx) And the following integrations: - **Langfuse** available through [LangfuseConnector](/docs/reference/pipeline-components/integrations/langfuse/LangfuseConnector.mdx) ## Naming Changes To make things clearer and better reflect what they’re for, we’ve updated a couple of names: - **Studio** is now **Pipeline Builder** - **Prompt Studio** is now **Prompt Explorer** The names have changed, but the functionality remains the same. ## Indexing Pipelines No Longer Required The range of scenarios deepset Cloud covers is growing, so we're adjusting to make workflows smooth and convenient. That's why indexing pipelines are no longer mandatory. You can have a pipeline with just the query part, and that's fine. This should make use cases like summarization or querying data in an external database, like Snowflake, smoother. For other use cases where you query data in one of the document stores integrated with deepset Cloud, we still recommend using an indexing pipeline to prepare your data. ## Labelling and V1 Templates Are Going Away Having analyzed the data, we've decided to deprecate the Labelling feature. You can use [Feedback ](https://docs.cloud.deepset.ai/docs/collect-feedback) to label your document search pipelines. We're also deprecating version 1 templates as we prepare to fully switch to version 2. Your version 1 pipelines will continue to work, but you won't be able to create them. --- ## Release 2024.12 Coming in December: workspace-level access, unrestricted file uploads, and the deprecation of experiments. *** ## Workspace-Level Access You can now control user access to workspaces. Previously, all users in your organization had access to all workspaces. Now, when you create a workspace, only you, as the creator, have access by default. You can invite others and assign them one of the following roles: - Admin - Editor - Search user To learn more, see [Manage User Access](/docs/how-to-guides/managing-access/manage-user-access.mdx). ## No Restrictions on File Types Upload any file type without limitations. Whether it’s documents, images, videos, or other formats, all file types are supported. This gives you the flexibility to manage the files you need without worrying about compatibility. For details, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). ## Experiments Are Going Away After reviewing the data, we've decided to focus on better tools for pipeline evaluation. We recommend using the Feedback feature to gather insights into your pipeline's quality and user needs. We're also developing a customizable tutorial to help you evaluate pipelines more systematically—stay tuned! For more information on feedback and evaluation, see [Evaluating Your Pipeline](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). --- ## Release 2024.8 August brings deepset Studio for easy pipeline editing. *** ## deepset Studio :::info Beta Release Studio is currently in a beta phase. This means you're getting an early look at what's coming. During this phase, we're fine-tuning it based on your feedback so you might run into some glitches. The full release is planned for September. ::: This release brings Pipeline Builder, a powerful visual editor designed to make building and editing even complex pipelines easier. With Pipeline Builder, you can enjoy: - An intuitive drag-and-drop interface to effortlessly build even complex v2.0 pipelines. This includes setting component parameters and defining connections validated in real-time. All this is enhanced with guidance on component compatibility and prefilled parameters, where applicable. - YAML integration to import and export your pipelines or switch to the YAML view whenever needed. Everything you do in Studio is automatically synchronized with the YAML editor. - A searchable component library accessible at all times to make it easy to choose the right building blocks for your pipelines. Check how to use Pipeline Builder: - [Create a Pipeline in Pipeline Builder](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx) --- ## Release 2024.9 September brings support for custom components in deepset Cloud! Check how they work. *** ## Introducing Custom Components Components are Python-based modules designed to perform specific tasks on your data. While deepset Cloud offers a rich library of out-of-the-box components, we understand your needs might call for specialized solutions. With our latest release, you can now create and integrate your own components directly into deepset Cloud pipelines. We provide a GitHub repository that serves as a template for your custom components. Follow the guidelines there to write your component, upload it to deepset Cloud, and your component will be ready to use. To learn more about custom components, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx). For instructions on how to create a custom component, see [Create a Custom Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-a-custom-component.mdx). See also a tutorial on creating a custom RegexBooster component: [Tutorial: Creating a Custom RegexBooster Component](/docs/tutorials/learn-more-advanced-features/tutorial-creating-a-custom-component.mdx). It guides you through writing the component but also uploading it to deepset Cloud and using in your pipelines. ## Editing Metadata in the UI Add, edit, and delete metadata from files in deepset Cloud: 1. Go to the Files page. 2. Find the file you want to modify, click _More actions_ next to it, and choose _View Metadata_. You can then modify the file's metadata as needed. --- ## Release 2025.10 October brings smoother pipeline editing with versions. *** ## Pipeline Versions Finally here: query pipeline versioning. Work on your pipelines until they're perfect without worrying about losing your previous progress. Every time you deploy your pipeline, it creates a new version you can later view, restore, and compare with another version. For details, see [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx). ## Run Pipelines Right in Builder You've already been able to run individual components in Builder. Now, you can run the entire pipeline directly in Builder without deploying. Just click **Run** in the top navigation bar, enter your query in the pop-up window, and see results right away. For details, check [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). --- ## Release 2025.11 November brings exciting updates to Agents and testing pipelines. *** ## Run Pipelines Right in Builder You've already been able to run individual components in Builder. Now, you can run the entire pipeline directly in Builder without deploying. Just click **Run** in the top navigation bar, enter your query in the pop-up window, and see results right away. For details, check [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). ## Easier Agent Configuration and Visual Tool Management Configuring an Agent in Builder just got easier: - New visual panel for agent settings: You can now configure your agent directly in the Builder UI. No more digging through the YAML editor. - Tools are visualized: See and manage your agent's tools on the agent component card. - Add MCP servers as tools without YAML: Add MCP servers right from the agent component card. Support for other tool types is coming soon. For details, check [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ## Running MCP Tools in Isolation Test your agent's MCP tools by running them individually from the agent component card. It's great for debugging or trying things out without running the whole agent. Click the agent card, choose the tool, and run it: For detailed instructions, see [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). --- ## Release 2025.12 Starting with December, you can add custom code to your pipeline using the new `Code` component. *** ## Introducing the `Code` Component Easily add custom Python code to your pipeline, without the need to create a full custom component. Just drag the `Code` component from the Component Library and add your code to the `code` parameter. The `Code` component is perfect for adding code that: - Is scoped to a single pipeline - Uses standard dependencies available in - Doesn't need to be shared with the rest of the organization - For instructions on how to add a `Code` component, see [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx). - For explanation of the component, see [Code Component](/docs/reference/pipeline-components/custom/Code.mdx). ## Pipeline Search History on the Pipeline Details Page View and download the search history for a pipeline right in . No need to use the API. Click the name of your pipeline to open its details and you'll find its complete search history, including all feedback, in the Search History tab. You can also download it as a CSV file with customized columns. ## Custom Code as an Agent's Tool Enhance your Agent with custom Python code as a tool. Choose `Code` as the tool type and let Builder guide you through the process. Your code is immediately validated so you can easily debug it before deploying the Agent. For an overview of how it works, see [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx). For instructions on how to add a custom tool, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ## AI Assistant for Custom Code We've added an AI assistant to the `Code` component and the code tool type for the Agent. Click **AI Assistant** in the code editor, type what you need, and let the AI work for you. No need to worry about the correct code syntax and the like. For details, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx) or [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx). --- ## Release 2025.2 January says farewell to v1 pipelines, adds MongoDB and together.ai integrations, and more. ## Naming Change deepset Cloud is now , or deepset for short. We're gradually updating the name across our product interface, documentation, and website. During this transition period, you may still see references to deepset Cloud. Bear with us while we complete this change. ## Easier Component Connections We've improved suggestions for component connections in Pipeline Builder. Now, when you click a connection point, you can see a list of popular and compatible components. Hover over a suggestion to view a tooltip with details about what the component does. All this to help you choose the most efficient connections for your pipelines. For details, see [Create a Pipeline in Pipeline Builder](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). ## Runtime Parameters in Jobs and Playground The query set for jobs now has the `params` column where you can provide runtime parameters for components in your pipeline. These parameters override the parameters set in the pipeline and are only used for queries from the query set. For details, see [Prepare a Query Set](/docs/how-to-guides/working-with-jobs/prepare-a-query-set.mdx). You can also change the parameters for individual components in Playground. That's the fastest and easiest way to test your pipeline configuration. Click the Configurations button in Playground, update components' parameters and ask a query. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). ## Streaming We added the `streaming_callback` parameter to the Generators, allowing you to configure the LLMs in your pipeline to stream. To enable streaming, set their `streaming_callback` to `deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback`. If your pipeline has multiple Generators, you can enable streaming for one or all of them. For details, see [Enable Streaming](/docs/enable-streaming). --- ## Release 2025.3 March brings a lot of improvements and exciting new features, like Agents. ## Agents in Your Pipelines Build intelligent pipelines that can autonomously perform tasks by making decisions, reasoning, and interacting with external tools. All of this is now available with Agents. You can find the Agent component in Pipeline Builder's Component Library. Simply add it to your pipelines, give it some tools, and let it do the work for you. The Agent uses an LLM through a `ChatGenerator` under the hood. You can configure pipeline components, whole pipelines, or custom functions as its tools. To learn more about what an AI Agent is, see [AI Agents](/docs/concepts/ai-agents/agentic-pipelines.mdx). To learn how to use the Agent component, see [Agent](/docs/reference/pipeline-components/ai/Agent.mdx). Eager to try it out? Use one of the pipelines we prepared, they're available in the Agents group on the Pipeline Templates page. ## Document Stores as Component Cards Document stores are now available as components in the Pipeline Builder. To add a document store to your pipeline, drag it from the Component Library and connect it to all components that need it. You can configure its parameters directly on the document store card. With this change, existing pipelines will now show a document store card connected to each component that requires one. - If the same configuration is used across components, a single document store card will connect to each of them. - If components need different configurations, you'll see a separate document store card for each one, connected to the appropriate components. To learn more about how document stores work, see [Document Stores](/docs/concepts/document-stores/document-stores.mdx). # New Pipeline Options ## Async Mode You can run your pipelines in async mode by setting `async_enabled: True` in the pipeline YAML. This is especially useful for pipelines with multiple branches, as it lets the components in different branches run concurrently. For details, see [Run a Pipeline in Async Mode](/docs/how-to-guides/designing-your-pipeline/run-a-pipeline-asynchronously.mdx). ## Output Type Setting Explicitly set your pipeline output type so that Playground can display its results in the best way. You can choose one of the following output types: - chat - generative - extractive - document Add the `pipeline_output_type` parameter to the pipeline YAML and set it to the desired output. For details on output types, see [Set Pipeline Output Type](/docs/how-to-guides/designing-your-pipeline/set-additional-params/set-pipeline-output.mdx). # 100 Workspaces We removed the limit of 10 workspaces per organization. Now, you can create up to a 100 workspaces per each organization. # Protected Shared Prototypes and Job Results Prototypes can now be restricted to logged in users that belong to your organization. When configuring a shared prototype, enable the Login required option. When a user accesses the prototype link, they'll be asked to log in first. For details, see [Share a Pipeline Prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). We added the same option for shared job results - you can choose if everyone with a link can view them or only people from your organization. Read also [Share a Job](/docs/how-to-guides/working-with-jobs/share-a-job.mdx). # Expanded Search User Permissions In addition to searching with pipelines and adding feedback, Search users can now run and share jobs within the workspace they have access to. They can also share results of jobs created by other users in that workspace. For details, see [Manage User Access](/docs/how-to-guides/managing-access/manage-user-access.mdx). # New Integration: Sync Your Data with Airbyte Airbyte is an open-source data integration platform designed to move data from various sources to destination. You can now use it to synchronize your data to . We added a deepset destination and a deepset connector to make it possible. Currently, it's limited to sources that support `FileTypeFormat`: Microsoft OneDrive, Microsoft SharePoint, Google Drive, and S3. For detailed instructions, see [Synchronize Data Using Airbyte](/docs/how-to-guides/working-with-your-data/synchronize-data-using-airbyte.mdx). --- ## Release 2025.4 See what updates April brings. ## Reusable Indexes This April, we’ve introduced a major update to how data indexing works in deepset. Indexes are now standalone resources, fully independent from pipelines. Here’s what that means for you: - Reuse data across pipelines. You only need to index your data once, then connect it to as many pipelines as you like. - Simplify debugging. Indexing logs are now separate from pipeline logs, making it easier to track and troubleshoot. - Share indexes across pipelines. Use the Document Store component to connect any index to your pipelines. To help you get started, we’ve added a new Indexes section where you can manage all your indexes. You’ll also find ready-to-use templates to create indexes quickly and easily. 🎥 Watch the video to see the simplest way to create an index and connect it to a pipeline: To understand indexes, check [Indexes](/docs/concepts/indexes/indexes.mdx). To learn how to create and enable indexes, see [Working with Indexes](/docs/how-to-guides/working-with-indexes/create-an-index.mdx). ## Access to Multiple Organizations Users can now be members of multiple deepset organizations. To add an organization and grant user access, reach out to your deepset representative. When granted access, you can switch between your organizations using a list on the Organizations page: For details, check [Manage User Access](/docs/how-to-guides/managing-access/manage-user-access.mdx). # Status Page We have launched a deepset AI Platform Status Page to help you stay informed about the health and availability of our services. You can now visit [status.deepset.ai ](https://status.deepset.ai/)to check the general and search availability of the platform with breakdown per day. The page is connected to our monitoring system so the status is always up to date. Check also [deepset AI Platform Status](/docs/getting-started/deepset-ai-platform-status.mdx). --- ## Release 2025.5 May comes with enhancements to the Indexes page and simplified pipeline usage tracking. ## Index Details Page Updates We've added the **Files** tab where you can check the details of each processed files, including the status, preview, and more. Click the index name to open the Index details page and check your files: ## Easier Usage Tracking We've simplified how your pipeline usage is measured. Now, everything runs on credits, including the time your pipelines are deployed and your indexes are processing files. Document storage units stay the same. For details, see [Understand Your Pipeline Usage](/docs/how-to-guides/productionizing-your-pipeline/understand-pipeline-usage.mdx). ## A MongoDB Atlas Template To give you an easier start, we added a MongoDB RAG Chat pipeline template, powered by GPT-4o. You can find it in the _Conversational_ category. It uses a MongoDB Atlas database as a document store and with the right setup, it works out of the box. Check the [Tutorial: Building a RAG Chat App with MongoDB Atlas Document Store](/docs/tutorials/learn-the-basics/tutorial-building-rag-with-mongodb.mdx) for detailed steps on how to set up the MongoDB database. --- ## Release 2025.6 Check what's coming in June. *** # Components in Builder Stick We've made a small but mighty improvement to Pipeline Builder. When you arrange components on the canvas, they'll stay exactly where you left them. No more rearranging every time you open a pipeline. Your custom layout is saved automatically. # Haystack Pipelines in deepset Bring your Haystack pipelines into deepset AI Platform using our SDK. All you need is a few lines of code and you can visualize and deploy your pipelines on the platform. For detailed instructions, see [Import a Haystack Pipeline](/docs/how-to-guides/designing-your-pipeline/import-a-pipeline.mdx). # Give Your Pipeline Something to Read Upload files directly in Playground while trying out your pipeline. If there already are files in the workspace the pipeline's in, the pipeline uses both the workspace and the Playground files to come up with responses. For details, see [Testing Your Pipeline](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). --- ## Release 2025.7 Check what's coming in July. *** # Service API Keys for Systems Integration You can now create service keys—purpose-built API keys for integrating with third-party apps, services, or automated jobs. They offer: * Clear separation between user and system activity * Better attribution for requests * Production-ready security and reliability **Tip**: You can also update existing API keys to act as service keys. To learn more, read [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). --- ## Release 2025.8 August adds governance features and revamped settings. *** ## Role-Based Access Control (RBAC) Control who can access your workspaces. Invite users and assign them roles to control their permissions. Roles determine what each person can do, and permissions are managed at two levels: * Organization * Workspace You can use a preset role with predefined permissions or you can create your own roles with custom permissions for assets in workspaces. To learn more, see: * [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx) * [Manage Users](/docs/how-to-guides/managing-access/manage-users.mdx) ## Revamped Settings All settings are now available in one place. Click your profile icon to open them and manage both organization and workspace settings, including: * Members and roles * API keys, secrets, and integrations Take a look, and if you need guidance, see [Updating Settings](/docs/getting-started/update-settings/updating-settings.mdx). --- ## Release 2025.9 Test individual components before deploying the whole pipeline. *** ## Run Individual Components We've enhanced Pipeline Builder so that you can run individual components in a pipeline or standalone. Just click the component card to bring up additional actions and then click Run. You can use this option to test the component input and output and understand how it processes data. To learn more, see [Run Components in Isolation](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). --- ## Release 2025.1 January comes with a bunch of updates, such as Airbyte integration or new URL for US deployments. Read on to learn more. *** # Airbyte Integration deepset Cloud is now integrated with [Airbyte](https://airbyte.com/), a popular open source data integration tool. We've added the deepset destination connector to Airbyte. You can use it to automatically sync your data sources and seamlessly transfer them to deepset Cloud. Check the connector documentation at [Airbyte](https://docs.airbyte.com/integrations/destinations/deepset). See also [Synchronize Data Using Airbyte](/docs/how-to-guides/working-with-your-data/synchronize-data-using-airbyte.mdx). # Deprecating V1 Pipelines On January 15, we're deprecating v1 pipelines. This means the v1 pipelines stop running and are no longer supported. We encourage you to use our robust v2 pipelines which offer much greater flexibility, including loops and multiple branches. For more information, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). # Haystack Experimental Features Available Through Custom Components Haystack, deepset's open-source LLM framework which is the underlying technology for deepset Cloud offers experimental features available in the `[haystack-experimental](https://github.com/deepset-ai/haystack-experimental)` package. While these features are not available in Pipeline Builder by default, you can add them through custom components. For details, see Custom Components and deepset Cloud and Haystack. (to do: add links once these are published) # Environment Selection When using API or the SDK, you can now choose the base URL (or the environment) for your deepset Cloud deployment. If you're making calls using our interactive API documentation, simply switch the `Base URL` option to the desired value: ![Base URL selection in the API docs](/img/getting-started/base_url.png) You can choose between Europe and US deployments. For details, see [API Structure and Organization](https://docs.cloud.deepset.ai/reference/api-overview#base-url). When using the SDK, you can pass the environment in the `api_url` parameter or choose `us`, `eu`, or `custom` when setting up the SDK with the `deepset-cloud login` command. For details, see [Set Up the SDK CLI](/docs/how-to-guides/working-with-the-sdk/using-the-command-line-interface-cli/set-up-the-sdk-cli.mdx). --- ## Release 2026.1 Coming in January: AI tools for documentation, the possibility to try out new features, and more. *** ## MCP Server for Documentation The documentation is now available as an MCP server that you can connect to your AI assistant to search this documentation directly. The server URL is: ``` https://docs.cloud.deepset.ai/api/mcp ``` You can copy it and add to your AI assistant's settings. For detailed instructions, see [Using Haystack Enterprise Documentation with AI](../using-docs-with-ai.mdx). ## Easy Copying of Documentation Pages To make the documentation easier to use with LLMs, we've added a new **Copy** button to the top right corner of each documentation page. The button copies the page as Markdown you can paste into an LLM chat window. You can also export the page as PDF or Markdown using the button. We hope this helps! ## Agent Improvements We're continuing to work on the Agent component. This January, we're bringing two improvements: - Pipeline tools in Builder: You can add existing pipelines as tools to your Agent using the visual panel. For details, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). - Advanced Agent configuration tab: Configure advanced model and agent parameters on the Agent component card. For details, see [Configure an Agent: Advanced Settings](/docs/how-to-guides/building-agents/configuring-agent-advanced.mdx). No more YAML editing for Agent configuration. You can do it all in the visual panel. --- ## Release 2026.2 Coming in February: GPU acceleration for pipelines, editable Agent tools, simplified versioning, and more control over pipeline usage. *** ## GPU Acceleration for Pipelines You can decide if your pipeline or index needs a GPU to run faster. Turn on GPU acceleration in the pipeline settings to enable it. If enabled, GPUs are only used when required and are not reserved for the entire pipeline run. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). For instructions on how to enable GPU acceleration, see: - [Enable GPU Acceleration for Pipelines](/docs/how-to-guides/designing-your-pipeline/set-additional-params/enable-gpu.mdx) - [Enable GPU Acceleration for Indexes](/docs/how-to-guides/working-with-indexes/enable-gpu-indexes.mdx) ## Pipeline Editing: One Editor at a Time and Linear Version History We've updated how pipeline editing works when more than one person works on the same pipeline. From now on, only one person at a time can edit a pipeline. While edited, the pipeline is locked for 60 seconds so others don't overwrite the same version. Deploy always uses the latest version of the pipeline, so you can deploy quickly without choosing between drafts and versions. ## Agent Tools Editable From the Agent Component As promised, we're continuing to work on the Agent component. This February, we're bringing editable Agent tools. You can now edit agent tools directly from the Agent component card in Builder. No need to leave the canvas to change tool settings. ## Control Your Pipeline Idle timeout Unused pipelines become idle after a period of inactivity to save resources. By default, development pipelines become idle after 20 minutes and production pipelines after 24 hours. Now, you can control the idle timeout and customize it to your needs: 1. Go to **Pipelines** and click the pipeline whose timeout you want to change. This opens the Pipeline Details page. 2. Go to **Settings** and adjust the idle timeout. You can also allocate replicas to your pipeline to ensure it's always available. For more information, see [Pipeline Scaling](/docs/concepts/about-pipelines/about-pipelines.mdx#pipeline-scaling). ## Smarter AI For Custom Code We've revamped the code component and made the AI in there smarter by: - Teaching it what code dependencies are already available in . - Giving it 's documentation as context. - Showing it the code of the component it's editing. For help adding custom code to your pipelines, see [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx). ## New Homepage We've redesigned the homepage to help you move faster. Now you can: - Create pipelines and indexes directly from the homepage. - See your totals at a glance, including deployed pipelines and enabled indexes in your workspace. If you need more details, click the top of the page to see full statistics, including total and latest searches and total files and documents. ## Simplified Component Connections We've made component connections more flexible to make things easier and get rid of "glue" components. You can now connect multiple components that output lists to a single component that accepts a list as input, without the need for a `ListJoiner` component. We've also added basic conversion from `string` to `ChatMessage` and the other way around. For details, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). ## Command Palette Find things faster with the command palette. Press **Cmd+K** (macOS) or **Ctrl+K** (Windows) to open it from anywhere in the platform. You can use it to quickly access your recent work, search documentation, find pipelines by name, and jump to any page or section directly, saving you multiple clicks. --- ## Release 2026.3 See what's coming in March. *** ## Command Palette Find things faster with the command palette. Press **Cmd+K** (macOS) or **Ctrl+K** (Windows) to open it from anywhere in the platform. You can use it to quickly access your recent work, search documentation, find pipelines by name, and jump to any page or section directly, saving you multiple clicks. ## LLM Component Say hello to the `LLM` component. `LLM` is a simplified version of the Agent that focuses solely on text generation without tool usage. It replaces `ChatGenerator` with `ChatPromptBuilder` and simplifies your pipelines. `LLM` supports system prompts, templated user prompts with required variables, and you can use it with any LLM provider. Try it out! For details, see [LLM](/docs/reference/pipeline-components/ai/LLM.mdx). ## Smarter Component Connections Resulting in Simpler Pipelines We've simplified how components connect in pipelines. Components can now accept connections from multiple outputs of the same list type. For example, you can connect multiple retrievers directly to a ranker that accepts a list of documents, and the pipeline merges the lists into one automatically. This means you no longer need `DocumentJoiner`, `ListJoiner`, or `OutputAdapter` in most cases — your pipelines just got simpler. Pipelines also handle automatic type conversions between `string` and `ChatMessage` in both directions. This lets you connect components like a `ChatGenerator` to inputs that expect plain text, or pass a query directly to a `ChatPromptBuilder`, without any extra conversion steps. This is the first in a series of improvements to make building easier and faster. For details, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). For instructions on how to simplify your existing pipelines, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ## Rich Editor for Jinja2 Templates Both user and system prompts now support Jinja2 templates. We also added a rich editor to make them easier to write, with the following features: - Type `@` to view available variables from previous components in the pipeline. - Type `/` to view available functions. No need to worry about `ChatMessage` format in Jinja. Write your prompt as plain text, and the editor formats it for you. ## Pipeline Tools Now Work with Validation Warnings You can now add a pipeline as an agent tool even when it has validation warnings. Previously, any validation issue would block tool creation entirely. Now, if the pipeline can be used, the tool is created and any warnings are visible in the Agent Settings so you can review and fix them at your own pace. Pipelines with hard errors that prevent them from running are still blocked. For details, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). --- ## Release 2026.4 Check April's updates. ## New Component Library We've redesigned the component library. Components are now organized into groups by their function to make them easier to find and use. The component library itself is only visible in the visual view in Builder and you can expand and collapse it, whatever suits you best. The new look is enabled by default, but you can still switch back to the old look in Settings. ## Choose Pipeline Version in Playground You can now choose the pipeline version you want to test in Playground. By default, the deployed version or the latest saved version is used, but you can test any version you choose. ## New Feature in Command Palette The command palette just got an upgrade: when you're on the Builder canvas, press **CMD + K** to search for any component in your pipeline and we'll take you right to it. No more scrolling around to find the right component. ## `Code` Component Updates ### Reusable Code Components You can turn a `Code` component into a saved custom component and reuse it across pipelines. After you write and test your code in Builder, choose **Save as Custom Component** to store it for your workspace or, with the right permissions, for your whole organization. Saved components show up in the **Custom** tab in the Component Library, so you and your teammates can drag them into any pipeline like built-in components. Each pipeline gets its own copy of the code, so you can iterate on the saved version without changing pipelines that already use an older copy. You can review and remove saved components from **Settings** at the workspace or organization level. For the full picture on custom components and the `Code` component workflow, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) and [Add Custom Code](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/add-custom-code.mdx). ## Save and Reuse Custom Model Definitions Save custom model definitions with your preferred parameters in Integrations and reuse them across pipelines. Once saved, your model shows in the model list anywhere it's supported, like `LLM` or `Agent` components. You can use it instantly without reconfiguring settings. Each reused model is a separate instance, so changes to the saved definition don't affect existing pipelines. You can also choose the scope of the model: workspace or organization. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ## Deprecated Update Pipeline API Endpoint The `Update Pipeline` API endpoint has been deprecated. Use the [Update Pipeline Settings](/docs/api/main/update-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-patch.api.mdx) and [Update Pipeline YAML Configuration](/docs/api/main/patch-query-pipeline-version-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-versions-version-id-patch.api.mdx) endpoints instead. For details, see [Edit Pipeline](/docs/how-to-guides/designing-your-pipeline/edit-a-pipeline.mdx). We'll continue to support the `Update Pipeline` endpoint for two months after the release of this version. ## Pipelines Are Getting Simpler We're still working on simplifying pipelines so that they're easy to build and maintain. In this release, we've eliminated the need for `DeepsetChatHistoryParser` and `AnswerBuilder` in most cases. You can now connect `Input`'s `messages` output directly to the `Agent`'s or `LLM`'s `messages` input. `messages` include prior conversations from the search history. Also, you no longer need `AnswerBuilder` in most cases. You can connect `LLM` or `Agent` directly to the `Output` component. For details, see [Simplify Pipelines](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ## Search History Leveled Up We've turned the pipeline's search history into a powerful, customizable workspace so you can explore, understand, and revisit past queries like never before. Here's what's new: - See the full story: Every query now lives in its original chat. Jump back in and get the complete context instantly. - Go deeper with details: From user, answer, and rating to timestamps, query IDs, and reference metadata—you've got the full picture at your fingertips. - Make it your own: Customize your table view by choosing the columns that matter most to you. It's everything you need to connect the dots, uncover insights, and keep things moving faster and smarter. For details, see [Search History](/docs/concepts/about-pipelines/about-pipelines.mdx#search-history). ## Choose the Components to Stream Define which components stream results to the UI. Add `streaming_components` to the pipeline YAML and list all components that should stream their outputs. For details, see [Streaming Components](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). ## Groups Now Available for Index Pipelines You can now use the Groups feature when building index pipelines in Pipeline Builder. Groups let you visually organize components, collapse them to reduce clutter, and keep related steps together. Groups are saved with your index and restored when you reload the builder. For details, see [Create an Index](/docs/how-to-guides/working-with-indexes/create-an-index.mdx). ## Image Files Now Preview Correctly Image files uploaded to a file-in/file-out pipeline now render as images in Playground, instead of showing a broken preview. This applies to PNG, JPG, GIF, and WEBP files displayed in the chat, documents preview, sources, and references panels. --- ## Release 2026.5 Check what's coming in May. ## Builder Updates ### Semantic Search in Builder Search for components in Builder using natural language queries. This is a powerful feature that helps you find the right components for your pipeline quickly and easily. To find a component: 1. In Builder, open the Component Library. 2. Type your query in the search bar using natural language. For example, "generate text from documents" or "rank search results by relevance". The library will suggest components that match your query. ### Improved File Preview in Playground Uploaded file previews in Playground now work correctly for all supported file types. Image files (PNG, JPG, JPEG, GIF, WebP, SVG) now display inline as images instead of being treated as binary content. Other file types also benefit from improved MIME type detection, so PDFs, text files, and other formats render reliably after upload. For details on supported preview formats, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). ### Organizing Components with Groups Group components to organize them and make your pipelines more readable. Groups help you keep related components together and you can collapse them to reduce visual clutter. To create a group, click the **Groups** button (group icon) in the bottom right corner of the canvas. Then click and drag on the canvas to draw a rectangle around the components you want to group. Keyboard shortcut: Press **Cmd+G** (Mac) or **Ctrl+G** (Windows/Linux) to activate group drawing mode, then draw the rectangle. Press **Esc** to cancel drawing mode. Groups are saved with your pipeline and restored when you reload the builder. ## Download Answer from Playground You can now download the answer text from a search result directly in Playground. Click the download icon next to an answer to save it as a Markdown file. The download icon appears alongside the existing copy icon and is available whenever an answer is displayed. For details, see [Test Your Pipeline in Playground](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). ### MultiRetriever Component You can now use the **MultiRetriever** component in Pipeline Builder to query multiple indexes and document stores in a single pipeline step. Configure each knowledge source with its own document store, index, and retriever strategy (BM25, embedding, or hybrid). Results from all sources are combined into a single list of documents passed to downstream components. Key capabilities: - Add, edit, and remove knowledge sources directly from the component drawer. - Mix retriever strategies across sources: use keyword-based BM25 for one index and embedding-based retrieval for another. - Select a query embedder (deepset NVIDIA, SentenceTransformers, or FastEmbed) for sources that use embedding or hybrid retrieval. - The embedding model syncs automatically from the selected index when compatible. For details, see [MultiRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiRetriever.mdx). ## Prompt Explorer: Updated Prompt Saves as a New Version When you click **Update** in Prompt Explorer, the updated prompt is now saved as a new pipeline version instead of being deployed automatically. Your current draft and the deployed version remain unchanged. To make the updated prompt live, deploy the new version manually. For details, see [Using Prompt Explorer](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx). ### Updated Default Reranker Model for `DeepsetNvidiaRanker` New pipelines that use `DeepsetNvidiaRanker` now default to the `tomaarsen/Qwen3-Reranker-0.6B-seq-cls` model. The previous default models (`intfloat/simlm-msmarco-reranker`, `BAAI/bge-reranker-v2-m3`, and `svalabs/cross-electra-ms-marco-german-uncased`) are decommissioned and no longer selectable for new pipelines. Existing pipelines that use one of these models continue to work without any changes, and the model has a **legacy** label in the model list. ## Updated Editor Role The Editor role can now manage workspace members, including adding and removing them, and updating their roles. For details, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). ## Simpler Pipeline Versions Creating a new draft version no longer fails when a draft already exists. If you create a new draft and one already exists, the existing draft is automatically finalized and a new draft is created in its place. You only see a conflict error if another user is actively editing the existing draft. For details, see [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx). --- ## Release 2026.6 Check June's updates. *** ## New Models: Claude 5 Sonnet, Claude 5 Fable, and More Several new models are now available in the model selector. ### Claude 5 Sonnet and Claude 5 Fable Claude 5 Sonnet and Claude 5 Fable are now available as models through both the Anthropic and AWS Bedrock providers. Both models support up to 128,000 output tokens and include an *Adaptive Thinking Effort* parameter (`adaptive_thinking_effort`) that lets you control reasoning depth. Set it to `low`, `medium`, `high`, `xhigh`, or `max`. Claude 5 Fable on AWS Bedrock is available in the `eu-west-1` region. ### Updated Token Limits for Claude 4.6 and 4.7 The maximum output tokens for Claude 4.6 and Claude 4.7 models have been increased from 64,000 to 128,000 tokens. ### New Gemini Models Gemini 3.5 Flash and Gemini 3.1 Flash Light are now available. Both include a `thinking_level` parameter with options `minimal`, `low`, `medium`, and `high`. Gemini 3.1 Pro now supports a `medium` thinking level in addition to `low` and `high`. For information on using models in your pipelines, see [Language Models in Haystack Enterprise Platform](/docs/concepts/language-models-in-deepset-cloud.mdx). ## Image Preview Now Available in Files and Indexes You can now preview image files directly in the Files and Indexes pages. Click **View** next to any PNG, JPG, JPEG, GIF, WEBP, or SVG file to open it in the file viewer. Previously, image files did not show a **View** button even though the preview infrastructure was in place. For the full list of supported preview formats, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). ## Anthropic on Azure Now Available as a Custom Model Provider You can now use Anthropic on Azure as a provider when adding a custom model definition. Select **Anthropic on Azure** from the provider list in *Settings > Integrations > Custom Models* to configure models hosted on Azure through Anthropic Foundry. For details on setting up custom models, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ## Use Your Pipelines as MCP Tools You can now use your deployed pipelines as MCP tools, making them available to AI coding assistants like Cursor, VS Code, or Claude Code. In , this works at the workspace level: you create one MCP server for your workspace, then individually enable each pipeline as its tool. A pipeline is not available as a tool until you explicitly turn it on in the pipeline's settings. When an AI client connects to your workspace's MCP endpoint, it discovers all the pipelines you enabled and can call them as tools. Each tool can have its own name, description, and instructions to help the AI assistant understand when and how to use it. This means you can mix and match pipelines within a single MCP server — for example, a RAG pipeline for knowledge retrieval, a data processing pipeline for transformation tasks, and a summarization pipeline for document analysis — all accessible through one endpoint. For details, see [Use Your Pipelines as MCP Tools](/docs/how-to-guides/productionizing-your-pipeline/expose-pipeline-as-mcp-tool.mdx). ## Mem0 Memory Tools for Agents You can now give your Agent long-term memory using Mem0. Adding Mem0 Memory to an Agent creates two tools: one that stores memories and one that retrieves them. Both tools are scoped to individual users so each user's memory stays separate. The *store memory* tool lets the Agent save facts, preferences, and context from a conversation. The *retrieve memories* tool lets the Agent search those stored memories when answering the user. To add Mem0 Memory tools, open the Agent configuration panel, click **Add Tool**, and choose *Mem0 Memory*. You need a Mem0 API key, which is saved as a workspace secret. For details, see [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx#mem0-memory) and [Add Mem0 Memory Tools](/docs/how-to-guides/building-agents/configuring-agent.mdx#add-mem0-memory-tools). ### Save Pipeline Tools Despite Validation Errors You can now save a pipeline tool even when the underlying pipeline has validation errors, such as an embedding dimension mismatch or a schema error. Previously, pipeline tool creation was blocked in these cases. Now, validation messages remain visible so you can review and fix them, but they no longer prevent you from saving the tool. The tool validation response also includes a new `can_create` field that signals whether creation is allowed. For pipeline tools, `can_create` is `true` whenever a valid tool definition exists — even if the pipeline has errors. For MCP and other tool types, `can_create` is `true` only when there are no validation errors. For details, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ## Builder Updates ### New Layout We've revamped Builder to make the building experience complete. Now, you can switch between Builder, Playground, pipeline analytics, and settings all in one place. No more switching between pages. ### Simplified Component Layouts and Clearer Connections Building pipelines just got cleaner. We've redesigned component layouts to give you a more transparent view of your pipeline. Now, you configure components in a configuration panel that opens when you click the component card. We've also added an expandable Connections panel to help you understand how components are connected and how data flows through your pipeline. Expand it for a full overview, or click any component to inspect its connections up close. You can now also use the Command Palette to create connections. Press **CMD + K** to open it and type `connect` to see the available commands. ### Configure Code Component Init Parameters from the UI You can add `__init__` parameters to your `Code` components. Just make sure they have default values. When you add `__init__` parameters, they're shown on the Advanced tab on the `Code` component's configuration. String, number, boolean, and enum parameters each get a dedicated inline control. Complex types such as objects or dictionaries open in an expandable editor. Values you set on the **Advanced** tab are saved into the pipeline configuration automatically. For details, see [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx). ### Global Issues Panel Builder now has a global Issues panel at the bottom of the canvas, next to the Connections tab. It collects all validation and runtime issues in one place, so you don't have to hunt through individual components to find out what's wrong. When an issue appears, click **Inspect** next to it to jump directly to the affected component or connection and fix it. ### MultiRetriever Knowledge Source Improvements The **Add/Edit Knowledge Source** flow in the MultiRetriever component has been updated with several improvements. You can now connect external document stores such as Pinecone and Qdrant by typing the index name directly and entering connection credentials. Credential fields support workspace and organization secrets — select a saved secret from the dropdown to fill the field securely without exposing raw values. Retriever parameters are now fully exposed in the configuration panel, and knowledge source cards show a yellow warning indicator when required fields are not yet filled in. For details, see [MultiRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiRetriever.mdx). ### Model Picker in Component Drawers Components that use an embedded chat generator — such as `LLMMetadataExtractor` — now show a model picker in their configuration drawer instead of a raw YAML editor. Select a model from the dropdown, use the **Connected only** toggle to filter to models with active provider connections, and get connection alerts directly in the drawer if the selected model is not connected. This matches the model selection experience already available in `LLM` and `Agent` component drawers. This release also fixes false **Model not connected** warnings that previously appeared in the Issues panel for these components even when the provider was connected. ## Type Literal `@` and `/` in the Prompt Editor You can now type a literal `@` or `/` character in the Jinja2 prompt editor when configuring the prompt for the `LLM` or `Agent` components. Typing either character opens a list of available variables or functions, but if you press `Escape` after the list appears, the character is inserted into the prompt. ## More Control Over Pipeline Versions Two new actions are now available in the pipeline versions list in Builder: - **Finalize** — converts a draft version into a permanent, numbered version. Use this when you want to lock in a draft without deploying it. - **Set as default** — marks a non-draft version as the default. The default version is used by serverless inference endpoints when a request identifies a pipeline by name or ID but does not specify a version. Default versions appear with a gold star **Default** tag in the versions list. For details, see [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx). ## Search History Updates ### Notes and Hashtags on Search History Records Add text notes to individual search history records to help you keep track of important information. Use notes to record observations, flag interesting queries, or leave context for your team. Notes are shown in the Search History table on the Pipeline Details page and in the detailed view for each query. You can add, edit, and delete notes at any time. You can also add hashtags to group related records together. Both notes and hashtags are searchable. You can view and manage them if you enable the Notes and Hashtags columns in the Search History table. ## Validation Warnings No Longer Block Pipeline Deployment Pipeline validation messages are now split into two categories: errors and warnings. Only errors prevent a pipeline from being deployed. Warnings are informational hints about your configuration and do not block deployment — your pipeline deploys successfully even when warnings are present. Review warnings to make sure your configuration is intentional. For more information, see [Troubleshoot Pipelines and Indexes](/docs/how-to-guides/designing-your-pipeline/troubleshooting-pipeline-deployment.mdx). ### Validation Warnings No Longer Block Pipeline Tool Creation This same behavior now applies when adding a pipeline as an agent tool. If the pipeline you're adding has validation warnings but no hard errors, the tool is created successfully. Any warnings are stored on the tool and visible in the Agent Settings panel so you can review them. Only hard failures — such as a pipeline that cannot be parsed — block tool creation. For details on adding pipeline tools, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ### AI-Powered Feedback insights Use the AI-powered Feedback Insights panel to analyze feedback patterns and generate executive summaries to help you understand performance trends and identify areas for improvement. Click Search History on the Pipeline Details page, expand the Feedback Insights panel, and use one of the suggested prompts or your own query to get insights. ## Validation Warnings No Longer Block Pipeline Deployment Pipeline validation messages are now split into two categories: errors and warnings. Only errors prevent a pipeline from being deployed. Warnings are informational hints about your configuration and do not block deployment — your pipeline deploys successfully even when warnings are present. Review warnings to make sure your configuration is intentional. For more information, see [Troubleshoot Pipelines and Indexes](/docs/how-to-guides/designing-your-pipeline/troubleshooting-pipeline-deployment.mdx). ## Editor Role Can Now Manage Workspace Custom Models The Editor workspace role now has write access to workspace-scoped custom model definitions. Editors can create, update, and delete custom models in their workspace without needing an Admin role. Organization-level custom models remain Admin-only. For details, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx) and [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). --- ## Release 2026.7 July 2026 brings updates to how agent pipelines handle chat history and adds more control over pipeline versions. *** ## New OpenAI GPT-5.6 Models Three new GPT-5.6 model variants are now available on the platform: **GPT-5.6 Sol**, **GPT-5.6 Terra**, and **GPT-5.6 Luna**. You can select them in the LLM or Agent component configuration in Builder. GPT-5.6 models support a `reasoning_effort` parameter (`none`, `low`, `medium`, `high`, `xhigh`, `max`) and a `reasoning_summary` parameter (`auto`, `concise`, `detailed`) to control the depth and verbosity of the model's reasoning process. GPT-5.5 and GPT-5.5 Pro have also been updated with `reasoning_effort` (up to `xhigh`) and `reasoning_summary` support. You can set these parameters on the **Advanced** tab of the component configuration panel. ## More Control Over Pipeline Versions Two new actions are now available in the pipeline versions list in Builder: - **Finalize** — converts a draft version into a permanent, numbered version. Use this when you want to lock in a draft without deploying it. - **Set as default** — marks a non-draft version as the default. The default version is used by endpoints when a request identifies a pipeline by name or ID but does not specify a version. Default versions appear with a gold star **Default** tag in the versions list. For details, see [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx). ## AI Assistant in Builder Builder now has a built-in AI assistant you can chat with directly in the pipeline editor. Click **AI Assistant** to open the chat panel and start a conversation. The AI assistant was designed with debugging in mind — you can describe a pipeline issue, paste error messages, or ask it to help you understand unexpected behavior. But it's not limited to debugging: you can also use it to get help with pipeline design, understand how components work, or explore other use cases as you build. When you have issues listed in the Issues panel, you can also click **Fix with AI** next to any issue. The AI assistant opens, reasons through the fix, and can apply it for you. For details, see [Debug with Builder](/docs/how-to-guides/productionizing-your-pipeline/debug-with-pipeline-builder.mdx). ## Bedrock Prompt Caching Amazon Bedrock models now support prompt caching for system prompts. You can set the `system_cachepoint_config_ttl` for models hosted on Amazon Bedrock to cache your system prompt for 5 minutes (`"5m"`) or 1 hour (`"1h"`), reducing latency and cost for repeated requests that share the same system prompt. The system prompt must stay static, with no parameters, for the cache to work. For details, see [AmazonBedrockChatGenerator](/docs/reference/pipeline-components/legacy-components/AmazonBedrockChatGenerator.mdx) and [Use Amazon Bedrock Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx). ## Full Message History for Agent Pipelines You can now control how much chat history is replayed to agent pipelines on each turn using the `chat_history_granularity` setting. By default, the platform sends only user query and final answer pairs to the pipeline (`QUERY_ANSWER`). Setting granularity to `ALL_MESSAGES` sends the complete message trace from the previous turn — including tool calls, tool results, and reasoning steps — so agents retain full context across follow-up requests. You can set this per request through the API or as a pipeline-level default in the pipeline YAML under `history.granularity`: ```yaml history: granularity: all_messages ``` The API field `chat_history_granularity` accepts `ALL_MESSAGES` or `QUERY_ANSWER` (uppercase). The YAML field accepts lowercase values. If both are set, the API request value takes priority over the YAML default. For details, see [Agent Memory](/docs/concepts/ai-agents/agent-memory.mdx). ## Search History Export Improvements ### Pipeline Version ID in CSV Export You can now filter the search history CSV export by pipeline version ID. The export also includes a `pipeline_version_id` column. Each row shows the ID of the pipeline version that served the query, so you can compare behavior across versions or investigate queries tied to a specific deployment. ### Feedback Created At Column The Search History table and CSV export now include a **Feedback Created At** column that shows when a user submitted feedback for each query. This column is separate from **Created At**, which records when the query was made. The column appears by default in both extractive and generative pipeline history views. In the CSV, the column is named `feedback_created_at` and is empty when no feedback has been given for a query. For details, see [Monitor Pipeline Performance](/docs/how-to-guides/productionizing-your-pipeline/pipeline-performance.mdx). --- ## Release Notes Find out how we're enhancing the Haystack Enterprise Platform and what's new in each release. *** ## Release Naming We name releases by year and month. For example, Release 2026.5 is the release from May 2026, and Release 2025.12 is from December 2025. *** {useCurrentSidebarCategory().items.map((yearGroup) => yearGroup.type === 'category' ? ( {yearGroup.label} {yearGroup.items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} ) : null )} --- ## Working in Haystack Enterprise Platform # Working in In , you work within workspaces where you keep your data and pipelines. You can have multiple workspaces, each with different content. There are three interfaces (GUI, API, and SDK) you can use to interact with , depending on what's most convenient to you. ## Workspaces In , you work within organizations to which you were invited. Each organization may have multiple workspaces with different data. Pipelines and data are not shared among workspaces. Pipelines, indexes, files, and jobs are specific to a workspace. When you delete a workspace, all these data are deleted as well. When you create a workspace, only you, as the creator and the Admin users in the organization, have access to it. To permit other users to access your workspaces, you must grant them access. For details, see [Manage User Access](/docs/how-to-guides/managing-access/manage-users.mdx). After logging in, you land on the homepage, where you can view all pipelines and indexes in your workspace. You can also go to detailed statistics to check the number of files and documents and the details of searches run with your pipelines. These include the top answer (the answer with the highest relevance score) and the top file (the file containing the top answer). The search time is in seconds. You can quickly switch between workspaces. Just click the workspace name and choose the one you want to switch to. ### Navigation Here's an explanation of what each navigation item does: | Navigation Step | Action | |---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Workspace name | Switch between workspaces. Create a workspace (just type the name of the new workspace). You can create up to 100 workspaces. After creating a workspace, only the workspace creator and Admin users in the organization can access it. Grant access to other users if you want them to use your workspace. | | Home | Access the guided workflow to create a pipeline. Check your workspace statistics, like the number of files or latest searches. | | Files | Upload files. These are the files your pipeline uses for search. Manage existing files (view, delete, preview, filter by metadata). | | Indexes | Create indexes. Manage existing indexes: enable, disable, view details. Click an index name to view its details, the query pipelines using it, and logs. | | Pipeline Templates | Choose a template. View templates. | | Pipelines | Create pipelines. Manage existing pipelines organized by their service level (deploy, undeploy, edit, view pipeline details, share pipelines, and export user feedback). Click the name of a pipeline to check its details, such as feedback, queries, logs, and so on. | | Jobs | Schedule jobs to run asynchronously. Currently, you can run batch question answering across the files in the workspace. | | Playground | Test your pipelines. | | Prompt Explorer | Engineer your prompts, try out different prompts, and compare them across up to three pipelines. Choose a prompt from a library of curated prompts. | To access your personal settings, organization and workspace settings, connections to model providers, and documentation, click your name in the top right corner. ## Command Palette The command palette is a quick-access tool that lets you navigate faster. Press **Cmd+K** (macOS) or **Ctrl+K** (Windows) to open it from anywhere in the platform. Use the command palette to: - Quickly access your recent work. - Search documentation. Type a keyword to find relevant documentation without leaving the platform. - Find pipelines by typing their names. - Jump to any page or section directly, saving you multiple clicks. ## Settings Clicking your profile icon in the top right corner opens a menu with additional settings. Click **Settings** to access your personal settings, organization and workspace settings, including integrations and API keys. ## Three Interfaces You can work in through one of these interfaces: - An intuitive, user-friendly [graphical user interface](https://cloud.deepset.ai/dashboard), where you can see real-life updates and get immediate feedback on your actions. - [REST API](/docs/api/index.mdx) for a platform-independent way to communicate with . It supports all the tasks available in GUI. - An open source [SDK package](https://github.com/deepset-ai/deepset-cloud-sdk) you can customize. Currently, it contains methods for efficient file operations, such as upload or listing. --- ## Building AI Agents Design, build, and deploy secure and efficient AI agents using . *** ## About This Task In , you can build AI agents using the `Agent` component incorporated into a pipeline. The `Agent` is a pipeline component that uses an LLM to call tools and reason about its actions. You can include multiple Agents in a pipeline and connect them to other components to build complex systems. ### When to Use an Agent Building an AI Agent makes sense for the following use cases: - Multi-step tasks that require reasoning and decision-making. Cases when you can't predict the exact sequence of steps and the tools to use at each step. Examples: - Debugging code where the Agent needs to make hypotheses and try different solutions based on what it discovers. - Tool orchestration where tasks require coordinating multiple tools or APIs. Examples: - An Agent deciding whether to query a database, search the web, or call an API based on the user's question. - Dynamic planning when the path to the solution varies based on the user's input. Examples: - Customer support Agents that need to check the order status, process returns, or answer questions about the product based on the user's input. ### When an Agent Might Be Too Complex An Agent is a powerful tool but for some use cases it might be an overkill. Consider using a simpler alternative if: - The workflow is predictable. You can map out the logic and steps in advance. - Your application must be fast. Agents require multiple LLM calls which increases the response time. - Your application must be predictable and highly reliable. Agents are less predictable and may be harder to control and debug. For these use cases, a pipeline with tool calling or conditional routing may be a better fit. For approaches alternative to Agents, see [Agentic Pipelines](/docs/concepts/ai-agents/agentic-pipelines.mdx). # Build an Agent 1. [Build a minimal Agent pipeline.](/docs/how-to-guides/building-agents/creating-minimal-agent.mdx) 2. [Configure the Agent's model, prompt, and tools.](/docs/how-to-guides/building-agents/configuring-agent.mdx) 3. [Configure the Agent's Advanced Settings](/docs/how-to-guides/building-agents/configuring-agent-advanced.mdx) ## Tutorials - [Building a Deal Desk Agent with Search and Custom Code](/docs/tutorials/build-agents/tutorial-building-an-agent-with-tools.mdx) — Build an agent that searches pricing policy documents and applies discount approval rules with a custom code tool. - [Building an IT Helpdesk Agent with Multiple Knowledge Bases](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) — Build an agent that routes employee questions to the right knowledge base using two document search pipeline tools. --- ## Configure Agent's Advanced Settings # Configure an Agent: Advanced Settings Configure advanced model and agent parameters. *** ## About This Task - For full Agent component documentation, see [Agent](/docs/reference/pipeline-components/ai/Agent.mdx). - For an explanation of Agent's workflow, see [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx). ## Prerequisites Complete the following tasks before you start: [Configure an Agent: Model, System Prompt, and Tools](/docs/how-to-guides/building-agents/configuring-agent.mdx). ## Access Agent's Advanced Settings 1. In Builder, click **Model** on the Agent component card to open its configuration panel. 2. Switch to the **Advanced** tab. 3. Configure the settings as needed. The *Parameters* section contains model-specific settings. For details on how to configure the model, refer to the model's documentation. The *Other* section contains Agent-specific settings: - `max_agent_steps`: The maximum number of actions the agent can perform. For more complicated tasks, you may need to increase this value. Note that increasing this value may increase the cost and time of the task. - `exit_conditions`: The conditions that cause the agent to stop. For example, you can configure the Agent to stop after a tool is used or once the model returns a text response. - To stop the agent when it generates a text response, choose `text`. - To stop the agent after a specific tool is used, choose the tool's name from the list. - You can choose multiple exit conditions and the agent stops when any of the conditions is met. For example, to stop the agent when it generates a text response or after a specific tool is used, choose `text` and the tool's name. - `retry_on_tool_failure`: Automatically retries the agent if a tool call fails. This is useful if the tool call times out or temporarily fails. ## Configure a Different Model ### In Agent YAML You can choose a model other than those available in the *Model* list. This requires you to switch to YAML and set the model there. Model is provided to the Agent using the `chat_generator` parameter. Use the `chat_generator` parameter to do this. Make sure there is a `ChatGenerator` component for the model you want to use. Make sure is connected to the model provider. For details on how to connect, see [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). For example, to use a model hosted on Together AI, pass `TogetherAIChatGenerator` as the value of the Agent's `chat_generator` parameter: ```yaml agent: init_parameters: chat_generator: type: haystack_integrations.components.generators.togetherai.chat.chat_generator.TogetherAIChatGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["TOGETHERAI_API_KEY"], "strict": false} model: deepseek-ai/DeepSeek-R1 generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 ``` ### Through Custom Model Definition You can also create a custom model definition and use it in the Agent. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ## Set Chat History Granularity When an agent pipeline runs in a multi-turn conversation, the platform replays past conversation turns to the agent on each new request. You can control how much of the chat history is replayed. There are two modes: - `query_answer` (default): Only the user's query and the agent's final answer from each past turn are included. This is compact and works well for most conversational use cases. - `all_messages`: Every message from each past turn is included — tool calls, tool results, reasoning steps, and the final answer. Use this when the agent needs the full context of previous interactions, for example when follow-up requests depend on which tools were called or what results they returned. ### In the Pipeline YAML Set the granularity in the pipeline YAML under the `history` key: ```yaml history: granularity: all_messages ``` Accepted values are `all_messages` and `query_answer` (lowercase). The YAML setting acts as a default and is overridden by any value passed in the API request. For details on the available values, when to use each, and how to override the setting per request through the API, see [Enable Streaming: Stream Request Parameters](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx#stream-request-parameters). --- ## Configure an Agent # Configure an Agent: Model, System Prompt, Tools, and Memory Choose the Agent's model and tools and learn how the Agent component works. *** ## About This Task Configure the agent prompt and model and expand its capabilities by adding tools it can use. You can also add memory to the Agent through Mem0. You can add MCP servers, pipelines, custom code, and Mem0 Memory as tools. Make sure the tool's name and description are meaningful and help the Agent decide when to use the tool. Add instructions on how to use the tool in the Agent's prompt. ## Prerequisites - For an explanation of the Agent, its tools and memory, see [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx) and [Agent Tools](/docs/concepts/ai-agents/ai-agent.mdx). - For the `Agent` component reference and parameter documentation, see [Agent](/docs/reference/pipeline-components/ai/Agent.mdx). - Make sure is connected to the provider of the model you want to use. The Agent works with chat models that support tool calls. For details on how to connect, see [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). - To use custom model definitions, make sure they're added on the Integrations page in Settings. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). - For instructions on how to write prompts, see [Writing Prompts in ](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). - Understanding of pipelines and components in . For details, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). ## Configure the Agent ### Configure the Model and System Prompt 1. Click **Add** to open the component library and add the Agent component onto the canvas. 2. Click the `Model` field to open the Agent configuration panel and choose the model from the list. 3. Enter the system prompt for the Agent. ### Add an MCP Server as a Tool :::info MCP Tool The server must be a remote server. To use a local server, first deploy it to a remote server. ::: 1. In the Tools section of the Agent configuration panel, click **Add Tool**. 2. Choose *MCP Server*. 3. Choose the transport protocol supported by the MCP Server you want to connect to. You'll find this information in the MCP Server documentation. - Choose *Server-Sent Events (SSE)* to keep an open connection and receive real-time updates as they occur. - Choose *Streamable HTTP* to receive updates in chunks as they become available. 4. Give your server a name to help you identify it later. 5. Enter the server URL. 6. Optionally, enter an authentication token if the server requires one. :::tip MCP API Key If you enter the MCP API key when adding the tool, it's automatically added as a workspace secret with the MCP server name. ::: 7. Click **Connect**. The MCP server details open. 8. Set the tool call timeout. This is the maximum time in seconds the Agent will wait for a response from the MCP server. 9. From the list of available MCP tools, choose the tools you want to expose to the Agent. :::tip Running MCP Tools on Their own You can run MCP tools on their own from the agent component card. Click **Manage Tool** next to the MCP server and choose the tool to run. Use this to debug or test tools without running the whole agent. For details, see [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx) ::: #### Example Configuration ### Add Custom Code as a Tool You can add custom Python functions as tools to your Agent. The code must use the `@tool` decorator that automatically converts your function into a tool. Each tool must have a name, description, and parameters. For detailed explanation of custom code as tools, see [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx). 1. In the Tools section of the Agent configuration panel, click **Add Tool**. 2. Choose *Code* as the tool type. 3. Give the tool a name and type a description for it, then click **Create Tool**. This opens the code editor. 3. Enter the Python code for your tool function. The code must use the `@tool` decorator and must define a function that the Agent can call. Use Python's `typing.Annotated` to add descriptions to parameters. This helps the Agent understand what each parameter does. You can use the example code as a starting point. Your code is immediately validated so you can easily debug it before deploying the Agent. :::tip AI assistant You can also use the AI assistant to generate code for your custom tool. To do this, click the **AI Assistant** button on the tool card, write your request in the prompt, and watch how the code gets generated. ::: 4. Add a tool name and description. Make sure the name is unique and descriptive. Make sure the description clearly explains what the tool does. The Agent uses the tool's name and description to decide when to use it. :::tip Running Custom Tools on Their own You can run your custom tools on their own from the agent component card. In the Tools section, click the tool you want to run and then click **Run**. ::: ### Add a Pipeline as a Tool You can add an existing pipeline or create one from a template. Such pipeline becomes detached from the original pipeline, so any changes you make to the original pipeline don't affect the tool pipeline. You can edit the pipeline tool directly from the Agent component card. :::info Pipelines with Validation Warnings You can add a pipeline as a tool even if it has validation warnings, as long as the pipeline can be used. The tool is created and the warnings are visible in the Agent Settings so you can review and resolve them later. If the pipeline has errors that prevent it from being used, the tool cannot be created. ::: 1. In the Tools section of the Agent configuration panel, click **Add Tool**. 2. Choose *Pipeline* as the tool type. 3. In the Create Pipeline Tool window: 1. Choose if you want to start from an existing pipeline or from a template. - If you're starting from an existing pipeline, choose a pipeline from the list, and then choose the version you want to use. - If you're starting from a template, choose the template to use. 2. Enter a name and a description for the pipeline tool. Make sure they're meaningful as the agent uses them to decide when to use the tool. 3. Click **Add Pipeline Tool**. The Agent configuration panel opens. 6. Under Tools, click the pipeline you just added. 5. Choose the pipeline inputs and outputs you want to expose to the Agent: 1. Expand Pipeline Inputs. 2. Choose how you want the pipeline to receive its inputs: - Choose **LLM** for the agent to automatically generate the input and feed it to the pipeline. - Choose **State** to read the input from the agent's state. Input stored in state is the input that earlier components or tools generated. 3. Expand Pipeline Outputs and choose how to handle the pipeline's outputs: - Choose **LLM** to feed the pipeline output to the agent. This is useful if the agent needs to use the pipeline output in its next turn. - Choose **State** to store the pipeline output in the agent's state. This is useful if you want the output to be available to other tools or components in the pipeline. - Choose **Both** to store the output in both the agent's state and feed it to the agent. :::tip Running Pipeline Tools on Their own You can run pipeline tools on their own from the agent component card. In the Tools section, click the pipeline tool you want to run and then click **Run**. Use this option to debug or test tools without running the whole agent. For details, see [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). ::: ## Add Mem0 Memory Tools {#add-mem0-memory-tools} You can add memory to your Agent through Mem0. Mem0 Memory tools give your Agent long-term memory across conversations. Adding them creates two tools: one for storing memories (store_memory) and one for retrieving them (retrieve_memories). Both tools are scoped to individual users through a `user_id` that the platform injects automatically from the Agent's state. For an explanation of how Mem0 Memory tools work, see [Mem0 Memory](/docs/concepts/ai-agents/agent-tools.mdx#mem0-memory). :::info Mem0 API Key You need a Mem0 API key to use Mem0 Memory tools. When you add the tools, the key is stored as a workspace secret. You can reuse an existing secret if you've already added a Mem0 API key to your workspace. ::: 1. In the Tools section of the Agent configuration panel, click **Add Tool**. 2. Choose *Mem0 Memory*. 3. In the *API Key* field, choose an existing Mem0 API key secret from the list, or type a new key to save it as a secret. 4. Optionally, adjust the store memory tool settings: - *Tool name*: The name the Agent uses to identify and call the store memory tool. Defaults to `store_memory`. - *Description*: Explains to the Agent when to use this tool. Keep it clear and specific. 5. Optionally, adjust the retrieve memories tool settings: - *Tool name*: The name the Agent uses to identify and call the retrieve memories tool. Defaults to `retrieve_memories`. - *Description*: Explains to the Agent when to use this tool. Keep it clear and specific. - *Top K*: The maximum number of memories to return per retrieval call. Defaults to `5`. 6. Click **Add Mem0 Memory Tools**. The platform adds both tools to the Agent and automatically updates the Agent's `state_schema` to include a `user_id` field. This scopes each user's memories separately. :::tip Updating Mem0 Tools To change the tool settings after adding them, click **Manage Tool** next to the Mem0 Memory entry in the Tools section. ::: ## Tutorials See these tutorials for end-to-end examples of configuring an agent with tools: - [Building a Deal Desk Agent with Search and Custom Code](/docs/tutorials/build-agents/tutorial-building-an-agent-with-tools.mdx) — Configure a pipeline search tool and a custom code tool on the same agent. - [Building an IT Helpdesk Agent with Multiple Knowledge Bases](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) — Configure two pipeline search tools that route questions to different knowledge bases. --- ## Create a Minimal Agent Pipeline Start simple by creating a minimal Agent pipeline that passes the query to the Agent and returns the result. *** ## About This Task Create a minimal Agent pipeline to understand how to connect the Agent to other components and build more complex systems. In this pipeline, the Agent receives the user query and generates a response. ## Create an Agent Pipeline 1. In the left navigation, go to *Pipelines Templates>Create empty pipeline*. 2. Give your pipeline a name and click **Create Pipeline**. 3. Click **Add** to open the component library, find `Input` and drag it onto the canvas. 4. Now, drag the `Agent` component onto the canvas. 6. Connect `Input` to `Agent`. The Builder automatically connects `Input`'s `messages` output to `Agent`'s `messages` input. 7. On the Agent component card, click **Prompt**, and enter the following prompt in the **System prompt** field: ``` You are a helpful assistant. Answer the user's question. ``` :::tip Agent Output The Agent component has no output connections until you configure its prompt. Once you enter the prompt, you'll see `messages` as an output connection. ::: 8. Click **Add**, find `Output`, and drag it onto the canvas. Every query pipeline must end with the `Output` component. 9. Connect `Agent` to `Output`. The Builder automatically connects `Agent`'s `messages` output to `Output`'s `messages` input. 10. Save the pipeline. This is how the pipeline should look like: This is the pipeline YAML: ```yaml components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: system_prompt: |- {% message role="system" %} You are a helpful assistant. Answer user's question. {% endmessage %} user_prompt: required_variables: exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: connections: [] max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages outputs: messages: Agent.messages ``` ## Run the Pipeline 1. In Builder, click **Run Pipeline**. 2. Ask any question and see how the Agent responds. ## What To Do Next - [Configure the Agent's model, prompt, and tools](/docs/how-to-guides/building-agents/configuring-agent.mdx). Once you do that, you'll already have a powerful Agent with tools it can use to expand its capabilities. - If needed, [configure the Agent's advanced settings](/docs/how-to-guides/building-agents/configuring-agent-advanced.mdx), such as when it should stop, what to store in the Agent's state, and more. - Check out our Agent templates available in on the Pipeline Templates page. ## Tutorials Follow these step-by-step tutorials to see a complete agent built with tools: - [Building a Deal Desk Agent with Search and Custom Code](/docs/tutorials/build-agents/tutorial-building-an-agent-with-tools.mdx) — Combines a document search pipeline tool with a custom code tool. - [Building an IT Helpdesk Agent with Multiple Knowledge Bases](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) — Uses two document search pipeline tools to route between knowledge bases. --- ## Troubleshooting Agents Troubleshoot common issues with Agents. *** ## MCP Connection Error ## Pipeline Tool Shows Validation Warnings When you add a pipeline as a tool, deepset validates the pipeline before adding it. If the pipeline has non-fatal validation issues (warnings), the tool is still added to the Agent. The warnings are stored on the tool and are visible in the tool configuration. Warnings do not prevent the tool from being used, but you should review them to make sure the pipeline behaves as expected. To inspect the warnings, open the tool configuration in the Agent's *Tools* panel. If you see a hard validation error and the tool was not added, the pipeline has an issue that prevents it from being used as a tool. Open the pipeline in Builder, check the Issues panel for errors, and resolve them before trying to add the tool again. Click **Inspect** next to any error to jump to the affected component, or click **Fix with AI** to open the AI assistant, which reasons through the fix and can apply it for you. --- ## Change the Pipeline's Service Level The service level of your pipeline determines its reliability and scalability but also impacts your costs. You can change the service levels of your pipelines at any time. *** ## About This Task By default, new and undeployed pipelines are set at the draft service level. Undeployed production pipelines also become draft pipelines. When you deploy a pipeline, it becomes a development pipeline unless you explicitly set its service level to production. To sum up, the default service levels are: - Undeployed pipelines: draft - Deployed pipelines: development You can change the pipeline’s service level from the interface or through an API endpoint. To learn more about service levels, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). # Prerequisites A pipeline must be deployed to become a production pipeline. # Change the Service Level from the UI 1. In , go to **Pipelines**. 2. Find the pipeline whose service level you want to change and click its name. You land in Builder. 3. Do one of the following: 1. Switch the production toggle to change the pipeline’s service level to production. When you do this, the pipeline’s production hours start being metered. 2. Switch the production toggle off without undeploying the pipeline to change its service level to development. When you do this, development hours start being metered for this pipeline. 3. Undeploy the pipeline to change its service level to draft. No hours are metered for a draft pipeline. # Change the Service Level Through REST API - To set the service level to development or production, use the [`Update Pipeline`](/docs/api/main/update-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-patch.api.mdx) endpoint. - To set the pipeline to draft, undeploy it using the [`Undeploy Pipeline`](/docs/api/main/undeploy-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-undeploy-post.api.mdx) endpoint. ## Change to Production or Development Copy this code, replacing the workspace, pipeline name, and API key: ```curl --request PATCH \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines/ \ --header 'accept: application/json' \ --header 'authorization: ' \ --header 'content-type: application/json' \ --data ' { "service_level": "DEVELOPMENT" # to change to production, replace with "PRODUCTION" } ' ``` For more details, see [Edit a Pipeline](./edit-a-pipeline.mdx). ## Change to Draft Undeploying a pipeline changes its service level to draft. Copy this code, replacing the workspace, pipeline name, and API key: ```curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines//undeploy \ --header 'accept: application/json' \ --header 'authorization: ' ``` --- ## Create a Pipeline in Pipeline Builder Use an intuitive, low code, drag-and-drop interface to build your pipelines. Easily switch between visual and code representations. *** ### Running Components and Pipelines You can run single components to understand their inputs and outputs and check if they work correctly before you save and deploy the whole pipeline. For information on how it works, see [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). You can also run the whole pipeline without needing to deploy it first. Just click the **Run** button on the navigation bar. ### Understanding the Pipeline YAML Format
Expand to view the YAML explanation Every pipeline is backed by a YAML configuration. You can access and edit it directly by switching to the YAML editor in Builder. Any changes you make in the visual editor are reflected in the YAML, and the other way around. A pipeline YAML has four main sections: - `components`: Defines the components in your pipeline and their parameters. - `connections`: Defines how components pass data to each other. - `inputs`: Maps pipeline-level inputs to the inputs of specific components. - `outputs`: Maps component outputs to the pipeline's final output. #### Components Each entry under `components` defines a component by its name and type. The name is optional and is a label you choose; you reference it in `connections`, `inputs`, and `outputs`. The type is the fully qualified class path of the component, which you can find on the component's documentation page. :::tip Component Information You can drag a component from the Component Library onto the visual canvas and then switch to the YAML editor to see the component's definition. ::: Use `init_parameters` to configure the component. Nested components, such as document stores, are also defined inline here: ```yaml components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 ``` #### Connections The `connections` section defines how data flows between components. Each connection specifies a `sender` and a `receiver` in the format `component_name.output_name` and `component_name.input_name`: ```yaml connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents ``` #### Inputs The `inputs` section maps pipeline-level inputs to the inputs of specific components. Each key is a pipeline input name (for example, `query` or `filters`). The list under each key specifies which component inputs receive that value: ```yaml inputs: query: - "query_embedder.text" - "ranker.query" filters: - "embedding_retriever.filters" ``` #### Outputs The `outputs` section maps the pipeline's named outputs to specific component outputs. Each key is the name of a pipeline output, and the value is a `component_name.output_name` reference: ```yaml outputs: documents: "ranker.documents" ``` #### Example: Semantic Document Search Pipeline Here's a complete query pipeline that embeds the query, retrieves semantically similar documents, and re-ranks the results: ```yaml components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents inputs: query: - "query_embedder.text" - "ranker.query" filters: - "embedding_retriever.filters" outputs: documents: "ranker.documents" ``` This pipeline works as follows: 1. `query_embedder` converts the query into a vector embedding. 2. `embedding_retriever` uses that embedding to find the most semantically similar documents in the document store. 3. `ranker` re-ranks the retrieved documents by relevance. 4. The pipeline returns the re-ranked documents as its output.
## Prerequisites - To learn about how pipelines and components work, see [Pipeline Components](https://docs.cloud.deepset.ai/docs/pipeline-components) and [Pipelines](https://docs.cloud.deepset.ai/docs/about-pipelines). - To use a hosted model, [connect to model providers](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx) first so that you don't have to pass the API key within the pipeline. For Hugging Face, this is only required for private models. Once is connected to a model provider, just pass the model name in the `model` parameter of the component that uses it in the pipeline. will download and load the model. For more information, see [Language Models in ](/docs/concepts/language-models-in-deepset-cloud.mdx). - To reuse custom model definitions when you configure components in Pipeline Builder, make sure they're added on the Integrations page in Settings. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ## Create a Pipeline From a Template 1. Log in to and go to **Pipeline Templates**. There are templates available for various tasks. They work out of the box or you can use them as a starting point for your pipeline. 2. Find a template that best matches your use case, hover over it, and click **Use Template**. 3. Give your pipeline a name and click **Create Pipeline**. You're redirected to Builder, where you can view and edit your pipeline. Make sure you choose an index for your pipeline on the document store card. 4. Depending on what you want to do: 1. To test your pipeline, deploy it first. Click **Deploy** in the upper right corner, wait until it's deployed, and then [test your pipeline in Playground](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). You can also try it out directly in Builder by clicking **Run Pipeline** above the `Input` component. 2. To edit your pipeline, see Step 5 in [Create a pipeline from an empty file](./create-a-pipeline-in-studio.mdx#create-a-pipeline-from-an-empty-file). ## Create a Pipeline From an Empty File 1. Log in to and go to **Pipeline Templates**. 2. In the top right corner, click **Create empty pipeline**. 3. Give your pipeline a name and click **Create Pipeline**. You're redirected to Builder. 4. Add the inputs for your pipeline. Pipelines must start with the `Input` component. 5. Click **Add** to add components from the components library and define their connections. 6. To give your pipeline access to files from a workspace, add `Retrievers` with a matching `Document Store`. For example, to use `OpenSearchDocumentStore`, add `OpenSearchEmbeddingRetriever` or `OpenSearchBM25Retriever` to your pipeline and connect them to the `OpenSearchDocumentStore`. Choose the index for the document store. 7. Add the `Output` component as the last component in your pipeline and connect it to the component generating answers (in LLM-based pipelines, this is `DeepsetAnswerBuilder`). Optionally, connect the _documents_ output to it if you want them included in the pipeline's output. 8. Save your pipeline. ## What To Do Next - To share and test your pipeline, deploy it. Click **Deploy** in the top right corner of Builder. - To test your pipeline, wait until it's indexed and then go to **Playground**. Make sure your pipeline is selected, and type your query. - To view pipeline details, such as statistics, feedback, or logs, click the pipeline name and switch to **Analytics**. - To let others test your pipeline, [share your pipeline prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). - If your pipeline contains components that work better on a GPU, turn on GPU acceleration. For details, see [Enable GPU Acceleration for Pipelines](/docs/how-to-guides/designing-your-pipeline/set-additional-params/enable-gpu.mdx). --- ## Create a Pipeline with REST API Upload a pipeline to using an API endpoint. Use this method if you have a pipeline YAML ready. *** ## Prerequisites - To learn about how pipelines and components work in , see [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx) and [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). - To use a hosted model, [Connect to Model Providers](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx) first so that you don't have to pass the API key within the pipeline. For Hugging Face, this is only required for private models. Once is connected to a model provider, just pass the model name in the `model` parameter of the component that uses it in the pipeline. will download and load the model. For more information, see [Language Models in ](/docs/concepts/language-models-in-deepset-cloud.mdx). - [An API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) to connect to . - A ready pipeline to upload to in the YAML format. :::info YAML Export You can first build your pipeline in Pipeline Builder and then export it to YAML from there. :::
Pipeline YAML Explained Your pipeline definition file is in the YAML format. Make sure that you follow the same indentation structure as in this example: ```yaml Query Pipeline components: # This section defines your pipeline components and their settings component_1: # Give your component a friendly name, you'll use it in the sections below type: # You can find the component type in documentation on a component's page (here maybe a link to components' docs) init_parameters: # Customize the component's settings, to use default values, skip this component_2: type: init_parameters: parameter1: value1 parameter2: value2 connections: # Define how the components are connected # You must explicitly indicate the intpus and outputs you want to connect # Input and output types must be the same to be connected # You can check components outputs and inputs in documentation - sender: component_1.output_name # Here you define the output name this component sends to the receiver component receiver: component_2.input_name # Here you define the input name that receives the output of the sender component inputs: # List all components that need query and filters as inputs but aren't getting them from any other component connected to them query: # These components will receive the query as input - "component_1.question" filters: # These components will receive a potential query filter as input - "component_1.filters" outputs: # Defines the output of your pipeline, usually the output of the last component documents: "component_2.documents" # The output of the pipeline is the retrieved documents ``` An example pipeline: ```yaml Query pipeline components: chat_summary_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Rewrite the current question so that it is suitable for web search ONLY if chat history is provided. If the chat history is empty, DO NOT reformulate the question. Be cautious when reformulating the current question. Substantial changes to the current question that distort the meaning of the current question are undesirable. It is possible that the current question does not need any changes. The chat history can help to incorporate context into the reformulated question. Make sure to incorporate that chat history into the reformulated question ONLY if needed. The overall meaning of the reformulated question must remain the same as the current question. You cannot change or dismiss keywords in the current question. If you do not want to make changes, just output the current question. Chat History: {{question}} Reformulated Question: chat_summary_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-3.5-turbo" generation_kwargs: max_tokens: 650 temperature: 0.0 seed: 0 replies_to_query: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0] }}" output_type: str bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False hosts: - ${OPENSEARCH_HOST} http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 # The number of results to return query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: "intfloat/e5-base-v2" device: null embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "intfloat/simlm-msmarco-reranker" top_k: 8 device: null model_kwargs: torch_dtype: "torch.float16" qa_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: qa_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-3.5-turbo" generation_kwargs: max_tokens: 400 temperature: 0.0 seed: 0 answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # Defines how the components are connected - sender: chat_summary_prompt_builder.prompt receiver: chat_summary_llm.prompt - sender: chat_summary_llm.replies receiver: replies_to_query.replies - sender: replies_to_query.output receiver: bm25_retriever.query - sender: replies_to_query.output receiver: query_embedder.text - sender: replies_to_query.output receiver: ranker.query - sender: replies_to_query.output receiver: qa_prompt_builder.question - sender: replies_to_query.output receiver: answer_builder.query - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: qa_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: qa_prompt_builder.prompt receiver: qa_llm.prompt - sender: qa_llm.replies receiver: answer_builder.replies max_loops_allowed: 100 inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "chat_summary_prompt_builder.question" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the retrieved documents ```
## Create a Pipeline The endpoint accepts a JSON request body. Pass your pipeline YAML as the `query_yaml` string field, along with a unique pipeline `name`. You cannot create an empty pipeline. Use the following code as a starting point for your API request: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data "$(jq -n \ --arg name '' \ --rawfile query_yaml path/to/pipeline.yaml \ '{name: $name, query_yaml: $query_yaml, deepset_cloud_version: "v2"}')" ``` - In line 2, replace `` with the name of the workspace where you want to create the pipeline. - In line 5, replace `` with the API key. - In line 7, replace `` with a unique name for your pipeline. - In line 8, replace `path/to/pipeline.yaml` with the path to your pipeline YAML file. The example uses [jq](https://jqlang.org/) to read your YAML file and embed it in the JSON body. If you do not have jq installed, you can pass the YAML inline instead: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "name": "", "query_yaml": "components:\n ...\nconnections: []\n", "deepset_cloud_version": "v2" }' ``` Replace the `query_yaml` value with your full pipeline YAML. Use `\n` for line breaks inside the string. To validate your pipeline without saving it, add `?dry_run=true` to the request URL. See the [REST API endpoint documentation](/docs/api/main/create-pipeline-api-v-1-workspaces-workspace-name-pipelines-post.api.mdx). --- ## Create a Pipeline Create a pipeline from scratch or choose one of the available templates for an easy start. You can use a visual drag-and-drop editor or REST API. ## About This Task There are two ways to create a pipeline: - **[Using Builder](./create-a-pipeline-in-studio.mdx)**: Choose this method to create your own pipeline from one of the ready-made templates or from scratch using a visual drag-and-drop editor. Builder has a library of components you can choose from to build your pipeline. - **[Using API](./create-a-pipeline-with-rest-api.mdx)**: Choose this way if you already have a pipeline YAML file and want to programmatically upload it to . ## Before You Start Creating an AI system involves several stages, from conceptualizing the use case to fine-tuning the app performance. provides all the building blocks and infrastructure you need, and a robust API for easy integration to simplify the process. ### Define the Use case Understanding your use case is the first step in the process. Knowing how your system is going to be used determines your pipeline architecture and your data requirements. 1. Identify the problem your app will solve or the opportunity it will https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.document. This may be the need to find company resources in an internal database or to have a support system for customers in place. If there are any existing solutions, analyze them, focusing on their limitations, and try to understand how an AI-powered approach can be better. 2. Understand the target audience. Who will use your app? How will they benefit from it? Where will they use it, and how? What are their pain points? What outcomes will they expect to achieve through the app? 3. Define your app's goals and determine the features and functionalities it should have to achieve them. This includes your app's AI capabilities, such as summarizing or prioritizing certain information or having a human-like conversation. Some questions to consider are: - What type of an app do you need: question answering, document search, a summarization system, a chatbot, a system for finding similar documents, or something else? - Do you want the system to generate novel answers based on your data (like RAG systems)? - Do you want the system to find exact information in your data and highlight it (like an extractive system)? - Do you expect the users to ask proper questions or rather type in keywords? - Are there any additional considerations? ### Think About Your Data Once you decide on the system you're building, it's time to think about the data it will run on. The quality of your data and how you preprocess it has a great impact on your system's performance. At this stage: - Consider any information that should be included in the data. Do your files contain metadata? Do you want to use these metadata in your app? For example, to prioritize certain documents or as search filters? Have a look at [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx) to understand how you can benefit from the metadata in your files. Think about whether the app should prioritize certain types of documents, like the most recent ones or ones with specific metadata values? - Understand how your data is organized. Is the same information scattered across different files, or does each file contain different information? This can impact how you preprocess your files. If the information is scattered across files, you may want to split your documents into smaller chunks and set the `top_k` to a higher number. - Identify file types. Are all your files of one type, or is it a mixture? Make sure you use appropriate `Converters` in your index or use a ready-made template available in . The templates include common converters that should be able to handle your files. - Consider the language your data is in. Is it English, German, or any other language? Is it multilingual? Make sure you choose a model that can handle the language of your data or an appropriate pipeline template. ### Get Started Building an AI app is an iterative process. It's best to start testing as soon as possible and then tweak things based on the results. 1. [Upload your data](/docs/how-to-guides/working-with-your-data/upload-files.mdx). You don't need to think about preprocessing them at this point, but it's good to make sure your data are clean and usable. In this step, you're transferring your data to , where your pipeline can use them. 2. [Create a Pipeline](./create-a-pipeline-in-studio.mdx). We recommend starting with a ready-made template that best matches the type of system you want to build. The templates use various models. If you're unsure which one to choose, we recommend starting with gpt-4-turbo. You can always change it to another model later without any trouble. For more information about models, see [Language Models in ](/docs/concepts/language-models-in-deepset-cloud.mdx). 3. [Deploy your pipeline](../deploy-a-pipeline.mdx). Once it's deployed, you can [test it in the Playground](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). Now, you have a starting point for your system. It's time to test it and see how it performs. Ask your colleagues to help you test the pipeline. You can easily [share your prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx) with anyone without the need to create accounts or log in. Prototypes are customizable; you can add your logo and brand colors. While testing the pipeline, try asking questions your target users would ask and keep notes on your feedback. A couple of things to keep in mind: - Check the source documents to verify the pipeline retrieves relevant documents. If it doesn't, try changing your retrieval approach. For more tips, see [Improving Your Document Search Pipeline](/docs/how-to-guides/optimizing-your-pipeline/improving-your-document-retrieval-pipeline.mdx). - If you're using an LLM and the pipeline retrieves correct documents, but the answers are bad, try [changing your prompt](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx). For more ideas on improving your pipeline, see the *Optimizing Your Pipeline* section. --- ## Deploy a Pipeline After you create and save a pipeline, you must deploy it to share it, test in Playground, or set it at the production service level. Deploy always uses the latest version of the pipeline, so you can deploy without choosing between drafts and versions. *** ## About This Task When you deploy a new version of a pipeline or redeploy an existing one, the version that's already running keeps handling queries until the new version deploys successfully. Your pipeline stays available the whole time. If the new deployment fails, the current version keeps running, so there's no downtime. ## Deploy a Pipeline from the UI 1. In , click **Pipelines**. 2. In the In Development section, find the desired pipeline, and click **Deploy** next to it. The pipeline is moved to _Deployed_ and the deployment starts. :::tip Check Issues Before Deploying Before deploying, open your pipeline in Builder and check the **Issues** tab at the bottom of the canvas. It shows all validation problems that could cause the deployment to fail. Click **Inspect** next to any issue to fix it first, or click **Fix with AI** to open the AI assistant, which reasons through the fix and can apply it for you. ::: ## Deploy a Pipeline with the REST API Here's the code you can use. For more information about this endpoint, see [Deploy Pipeline API](/docs/api/main/deploy-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-deploy-post.api.mdx). You need to [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) first. Copy this code replacing workspace name, pipeline name, and API key: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines//deploy \ --header 'Accept: application/json' \ --header 'Authorization: Bearer ' ``` ## What To Do Next It may happen that the deployment fails, and the pipeline status is _failed to deploy_. This status means the pipeline wasn't deployed. If you encounter this error, you must take some [troubleshooting action](./troubleshooting-pipeline-deployment.mdx). To view pipeline information, such as statistics or feedback, click the pipeline name. It opens in Builder. Switch to *Analytics*. It contains all the information you may need. Deployed pipelines that haven't been used for a while become idle to save resources. The default idle timeout depends on the pipeline service level. By default, production pipelines go on standby after 24 hours of not being used and development pipelines after 20 minutes. You can customize the idle timeout in pipeline settings. An idle pipeline gets automatically activated if you run a search with it or you can trigger the activation manually on the Pipelines page. For more information, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). --- ## Edit a Pipeline Improve your pipeline to make your search faster and more accurate. You can edit pipelines in Pipeline Builder or through REST API. *** ## About This Task You can edit a development pipeline while it remains deployed. You can make the following changes: - Update components. - Update the index a pipeline is using. - Update the pipeline's name. Any changes you make create a new, undeployed version of the pipeline. :::info Production Pipelines You can't edit production pipelines. You must change the pipeline's service level first. ::: ## One Editor at a Time Only one person can edit a pipeline at a time. When someone saves changes, the pipeline is locked for 60 seconds so others cannot overwrite the same version. - **If you try to edit while the pipeline is locked:** You see a message like "[User A] edited this pipeline 30 seconds ago. You can edit in 30 seconds." - **After 60 seconds:** The lock expires. Click **Try again** to start editing. - **Why 60 seconds?** The lock prevents situations where people rapidly overwrite each other's changes, while still allowing sequential collaboration. The lock is based on time (60 seconds after the last save), not on whether the other person has the editor open. If someone leaves their browser open without saving, you can edit after 60 seconds from their last save. :::tip Need to Edit at the Same Time? If you often need multiple people to edit a pipeline at once, share your use case with us. We're tracking this to inform future collaboration features. ::: ## Prerequisites - You must be an Admin to perform this task. - If the changes you want to make require undeploying the pipeline, go to **Pipelines**, click the more actions button next to the pipeline name, and select **Undeploy**. - If you're updating the index the pipeline uses, make sure the index is enabled. For instructions, see [Enable an Index](../working-with-indexes/enable-an-index.mdx). - To edit pipelines using API endpoints, [generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) first. ## Edit a Pipeline in Builder This is the default way of editing pipelines. It opens the pipeline in the visual editor. You can use it to replace one component with another or update the parameters quickly. 1. Log in to and go to **Pipelines**. 2. Click the pipeline you want to edit. It opens in Builder. :::tip Renaming a Pipeline If you just want to rename a pipeline, you can do it from the More Actions menu without opening the Builder. Click **More Actions** next to a pipeline on the Pipelines page and choose *Rename*. 3. Modify the pipeline and save it. :::tip Updating the Index To update the index a pipeline is using, find the document store that uses the index you want to change and choose a different index. ::: 4. [Deploy the pipeline](./deploy-a-pipeline.mdx) to use it for search. ## Duplicate a Pipeline Duplicating creates a copy of a pipeline with its YAML configuration and runtime settings. Use this when you want to create a variant of an existing pipeline without changing the original. 1. Log in to and go to **Pipelines**. 2. Find the pipeline you want to copy, click the More Actions menu next to it, and choose *Duplicate*. 3. In the *New pipeline name* field, enter a name for the copy. The default name is `{source-name}-copy`. 4. Click **Duplicate**. You're taken to Pipeline Builder where you can edit the new pipeline. If a pipeline with the name you entered already exists, an inline error appears — enter a different name and try again. :::info Runtime Settings The duplicate includes the source pipeline's runtime settings (such as replica count, GPU acceleration, and idle timeout). If the settings can't be copied, you'll see a warning and can update them in the pipeline settings. ::: ## Edit a Pipeline with REST API ### Update Pipeline Settings Use the [Update Pipeline](/docs/api/main/update-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-patch.api.mdx) endpoint to change pipeline settings, such as name or service level, without changing the YAML configuration. #### Example Copy this code and modify it as needed: ```curl --request PATCH \ --url https://api.cloud.deepset.ai/api/v1//pipelines/ \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data ' { "name": "new_pipeline_name", "service_level": "DEVELOPMENT", "status": 1 } ' ``` ### Update Pipeline YAML Configuration For updating pipeline YAML configuration, use the pipeline versions API: 1. Fetch the latest version using [Get Query Pipeline Version](/docs/api/main/get-query-pipeline-version-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-versions-version-id-get.api.mdx). 2. Create a new draft version with [Create Query Pipeline Version](/docs/api/main/create-query-pipeline-version-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-versions-post.api.mdx). If a draft already exists, it is automatically finalized and a new draft is created. If the existing draft is currently locked by another user, the request returns a 409 Conflict error — wait for the lock to expire and try again. 3. Update the pipeline configuration using [Patch Query Pipeline Version](/docs/api/main/patch-query-pipeline-version-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-versions-version-id-patch.api.mdx). ## Related Information - [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx) - [Deploy a Pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) --- ## Import a Pipeline Import your Haystack pipeline into to visualize it and make further updates. *** ## Prerequisites You must have a Haystack pipeline in the YAML format. You can use the following code to serialize your pipeline: ```python from haystack import Pipeline pipeline = Pipeline() with open("/path/to/save/the/pipeline.yaml", "w") as file: pipeline.dump(file) ``` For more information, see Haystack documentation. ## Import Your Pipeline 1. Log in to and click **Pipeline Templates** in the navigation. 2. On the Templates page, choose **Create empty pipeline**. 3. Give your pipeline a name and click **Create Pipeline**. You're redirected to Pipeline Builder. 4. Switch to the YAML view using the code switch. 5. Copy your pipeline YAML, and paste it in the code editor. 6. Use the code switch to change to the canvas view and see your pipeline visualization. ## What's Next - To deploy your pipeline in , add the input and output components. For details, see [Inputs and Outputs](/docs/concepts/about-pipelines/about-pipelines.mdx#inputs). - Once you're done updating the pipeline, you can export it to YAML or Python using the **Download** button: --- ## Manage Pipeline Versions With versions, you can try different pipeline configurations without losing your past work. Currently, versions are available for query pipelines. *** ## About This Task Use pipeline versions to experiment with different configurations while keeping your previous work safe. When you work on a pipeline without saving it, it's a draft. Each time you make changes and save your pipeline, a new version is created. You can compare versions, restore previous configurations, and deploy specific versions when you're ready. The current pipeline draft automatically becomes a new version when you: - Save changes in Builder - Deploy a pipeline - Restore a previous version - Update a prompt in Prompt Explorer Each version includes the complete pipeline configuration and metadata about when it was created and by whom. If you duplicate a pipeline, its version history is not copied to the new pipeline. ### Version Status Tags Versions in the list can show the following status tags: - **Editing** — the version currently open for editing. - **Deployed** (green) — the version currently deployed and serving requests. - **Default** (gold star) — the version used by serverless inference endpoints when a request specifies a pipeline by name or ID but does not specify a particular version. ### Create a New Draft When One Already Exists Only one draft can be active for a pipeline at a time. If you create a new draft when one already exists, the existing draft is automatically finalized (saved as a numbered version) and a new draft is created in its place. If the existing draft is currently being edited by another user, you'll see a 409 error: "The current draft is being edited by another user." Wait until the other user finishes editing (or until their 60-second edit lock expires) and then try again. ### Restore a Version To restore a version: 1. When editing a pipeline in Builder, click **Versions**. 2. Find the version you want to restore, click **More Actions** next to it, and click **Restore**. 3. Confirm that you want to restore the version. Your current work is saved as a new version and the restored version opens for editing. ## Deploy a Version To deploy a previous version: 1. When editing a pipeline in Builder, click **Versions**. 2. Find the version you want to deploy, click **More Actions** next to it, and choose **Deploy**. This opens a comparison view where you can check the changes between the versions. 3. Click **Deploy**. The version you're deploying opens in Builder and the version you were previously working on is saved as a new version. :::info Redeploying When you deploy a new version of a pipeline or redeploy an existing one, the version that's already running keeps handling queries until the new version deploys successfully. Your pipeline stays available the whole time. If the new deployment fails, the current version keeps running, so there's no downtime. ::: ## Finalize a Version Finalizing converts a draft version into a permanent, numbered version. When a version is finalized, you can no longer edit it as a draft, but it remains available to deploy, restore, or set as default. To finalize a draft version: 1. When editing a pipeline in Builder, click **Versions**. 2. Find the draft version you want to finalize, click **More Actions** next to it, and click **Finalize**. The version is saved as a permanent numbered version. ## Set a Version as Default The default version is used by serverless inference endpoints when a request identifies a pipeline by name or ID but does not specify a particular version ID. You can set only non-draft versions as default. To set a version as default: 1. When editing a pipeline in Builder, click **Versions**. 2. Find the version you want to make the default, click **More Actions** next to it, and click **Set as default**. The version is marked with a gold star **Default** tag in the versions list. ## Compare Versions To see what changed between versions: 1. In Builder, click **Versions**. 2. Choose the version you want to compare with the current version and click the **Compare** icon. The differences are highlighted in the comparison view. ## Related Information - [Deploy a Pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) - [Edit a Pipeline](/docs/how-to-guides/designing-your-pipeline/edit-a-pipeline.mdx) --- ## Run a Pipeline in Async Mode Learn how to run pipelines asynchronously to efficiently handle long-running tasks. ## About This Task By default, pipelines run synchronously, meaning they execute components one after another, waiting for each to finish before proceeding. You can modify the pipeline YAML to enable async mode, allowing components in different branches to run in parallel. In async mode, components run in the background, so the system doesn't have to wait for one to finish before starting another. This can be useful when: - Multiple branches can run in parallel, reducing overall execution time. - A component needs to handle multiple requests simultaneously. (For this, the component must implement the `run_async` method. Otherwise, it falls back to sync.) ## Enable Async Mode 1. Log in to and go to **Pipelines**. 2. Click the pipeline you want to run async. It opens in Builder. 3. Switch to the YAML view. 4. Scroll down to the end of the YAML and add `async_enabled: True`, like this: ```yaml inputs: files: - file_classifier.sources max_runs_per_component: 100 metadata: {} async_enabled: True # enables async mode ``` 5. Save your pipeline. ## Related Information - [Deploy a Pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) - [Test Your Pipeline in Playground](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx) --- ## Run Components and Pipelines in Builder Run individual components independently in Builder to test, debug, and validate them before deploying your full pipeline. You can also run the pipeline right from the Builder. *** ## About This Task In Builder, you can run components and agent tools in isolation to test them without deploying the entire pipeline or index. Running a single component helps you: - Verify its configuration and parameters. - Validate input and output formats. - Identify issues in the configuration. - Understand how it processes data. - Experiment with different settings. This saves time by letting you validate components early, before deploying a full pipeline or index. You can also run the whole pipeline without deploying it first. ## Documents as Input When you run an individual component, Builder automatically fills in its input, except for components that require `documents`. For these, the input defaults to an empty array. To use real documents, first run a component that retrieves them (for example, a Retriever), and then click **Run Next** to use the retrieved documents as an input for the next component. All input must be valid JSON. ## Run a Single Component You can run a component that's already a part of a pipeline or you can drag and drop a single component on the canvas and run it there. 1. Choose how to run a component: - To run a standalone component: 1. Go to _Pipelines>Create Pipeline>Create empty pipeline_. 2. Give your pipeline a name and click **Create Pipeline**. 3. In Builder, click **Add**, find the component you want to run, and drag it onto the canvas. 4. Click the **Run** icon on the component card. - To run a component that's part of a pipeline: 1. Go to **Pipelines** and click the pipeline containing the component. This opens Builder. 2. Find the component to run and click **Run** on its card. This opens a window with the component input automatically filled in (except for components that take `documents`). You can edit the input and format it with the **Format** button. 3. Click **Run Component**. After the component runs, its output is displayed in an expandable editor. If the component is part of a pipeline, you can then click **Run Next** to run the next component in the pipeline. ## Run an Agent Tool Prerequisite: You must have a pipeline with the `Agent` component configured with tools. For details, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). 1. In Builder, click the agent card. This opens the agent configuration. 2. In the Tools section, click the tool you want to run. 3. At the top of the tool card, click **Run**. You may need to provide the tool input. After the tool runs, its output is displayed so you can verify the result. ## Run a Pipeline In Builder, click **Run Pipeline** above the `Input` component. A window where you can type your query pops up. --- ## Enable GPU Acceleration By default, pipelines run on CPU. You can enable GPU acceleration for a pipeline to speed it up. This is especially useful for pipelines that include components that run faster on a GPU, like custom components that use AI models. *** ## About This Task When you enable GPU acceleration, the pipeline checks whether a component needs a GPU and assigns one automatically. GPUs are only used when required and are not reserved for the entire pipeline run. If GPU acceleration is disabled and your pipeline includes components that rely on a GPU, those components run on the CPU instead. This can slow down processing and may cause timeouts, especially for larger or more complex pipelines. ## Enable GPU Acceleration 1. Go to **Pipelines** and click the pipeline you want to enable GPU acceleration for. This opens the pipeline in Builder. 2. Switch to **Settings**, scroll down to the GPU Settings section, and click the GPU Acceleration toggle to turn it on. --- ## Set Pipeline Output Type You can explicitly set the pipeline output type in YAML. This helps the Playground adjust its behavior to better support your pipeline. ## About This Task By setting the pipeline output type, you make sure the Playground displays results in the most relevant way. The platform can auto-detect the type, but this may not always be accurate. To avoid issues, we recommend setting it explicitly in YAML. If you set a type manually, it overrides the auto-detected one. For example, if your pipeline is generative but you set `pipeline_output_type: "chat"`, the Playground will use the chat view. ### Available Types You can set `pipeline_output_type` to one of these values: - `generative`: For pipelines where an LLM generates new text as a response. - `chat`: For conversational pipelines. - `extractive`: For pipelines that extract answers directly from documents. - `document`: For pipelines that return full documents or multiple documents as results. ### How Playground Adapts Expand each section to check how the Playground interface changes for each pipeline output type:
Generative pipelines For generative pipelines, the query input field is at the top of the page and the generated answers show below it:
Chat pipelines Playground adjusts to the chat view: When the user starts the conversation, it keeps previous questions and answers in view:
Extractive pipelines For extractive pipelines, the query input field is at the top and the extracted answers appear below it:
Document search pipelines For document search pipelines, the query input field is at the top: Once the user asks a query, the related documents are displayed on the page:
## Set the Pipeline Output Type 1. Log in to and go to **Pipelines**. 2. Find the pipeline you want to update and click its name. You land in Builder. 3. Switch to the YAML view. 4. Add the following line at the beginning of your pipeline YAML: ```yaml pipeline_output_type: "" # Choose one of these options: # pipeline_output_type: "generative" # pipeline_output_type: "extractive" # pipeline_output_type: "chat" # pipeline_output_type: "document" ``` 5. Save your pipeline. ## What To Do Next You can [deploy](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) your pipeline and [try it out in Playground](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). --- ## Simplify Pipelines with Smart Connections # Simplify Your Pipelines Remove unnecessary components from your pipelines by taking advantage of smart connections. Use this guide to learn how to simplify your pipelines. *** ## About This Task Smart connections let the pipeline automatically merge lists and convert types between components. This means many "glue" components you used before are no longer needed. Your pipelines become shorter, easier to read, and simpler to debug. | Component Previously Needed | Smart Connection Instead | | :--- | :--- | | `DocumentJoiner` | Connect all `document` outputs from sender components directly to one `list[Document]` input (example receiving components are `Ranker`, `PromptBuilder`, `DocumentSplitter`, `DocumentWriter`, `Embedder`, `AnswerBuilder`, typically to their `documents` input).| | `ListJoiner` | Connect all sender components' outputs directly to one `list[ChatMessage]` input (example receiver is Agent's `messages` input).| | `OutputAdapter` | Connect the LLM's `replies` output directly to the `Retriever`, `Ranker`, and other downstream components. | | [`DeepsetChatHistoryParser`](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx) | Configure the `Input` component to produce `messages` and connect its `messages` output directly to the `Agent`'s `messages` input. | For a full list of simplified components, see [Legacy Components](/docs/reference/pipeline-components/legacy-components.mdx). For background on how smart connections work, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). ## Remove DocumentJoiner Components now accept multiple lists of documents, which eliminates the need for a `DocumentJoiner` in most cases. Below, you can find common use cases for `DocumentJoiner` and how to simplify them. ### Hybrid Retrieval Pipelines If your pipeline uses multiple retrievers (for example, a BM25 retriever and an embedding retriever), you probably have a `DocumentJoiner` sitting between the retrievers and the next component. With smart connections, you can remove it and connect the retrievers directly to the downstream component. The pipeline automatically merges the document lists into one before passing them along. To simplify this pipeline: 1. Remove the `DocumentJoiner` component. 2. Reconnect `OpenSearchBM25Retriever`'s `documents` output to `TransformersSimilarityRanker`'s `documents` input. 3. Reconnect `OpenSearchEmbeddingRetriever`'s `documents` output to `TransformersSimilarityRanker`'s `documents` input.
Before: with DocumentJoiner ```yaml components: OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' embedding_dim: 768 http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 SentenceTransformersTextEmbedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' embedding_dim: 768 http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the question based on the provided documents. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-4o AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder connections: - sender: OpenSearchBM25Retriever.documents receiver: DocumentJoiner.documents - sender: SentenceTransformersTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding - sender: OpenSearchEmbeddingRetriever.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: TransformersSimilarityRanker.documents - sender: TransformersSimilarityRanker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: AnswerBuilder.replies inputs: query: - OpenSearchBM25Retriever.query - SentenceTransformersTextEmbedder.text - TransformersSimilarityRanker.query - PromptBuilder.question - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ```
After: without DocumentJoiner ```yaml components: OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' embedding_dim: 768 http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 SentenceTransformersTextEmbedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' embedding_dim: 768 http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the question based on the provided documents. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-4o AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder connections: - sender: OpenSearchBM25Retriever.documents receiver: TransformersSimilarityRanker.documents - sender: SentenceTransformersTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding - sender: OpenSearchEmbeddingRetriever.documents receiver: TransformersSimilarityRanker.documents - sender: TransformersSimilarityRanker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: AnswerBuilder.replies inputs: query: - OpenSearchBM25Retriever.query - SentenceTransformersTextEmbedder.text - TransformersSimilarityRanker.query - PromptBuilder.question - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ```
### Indexes with Multiple File Converters A common use case is to connect multiple file converters to a `DocumentWriter` in an index. To simplify such an index, do these steps: 1. Remove the `DocumentJoiner` component that collects documents from converters and sends them to `DocumentSplitter`. 2. Reconnect `TextFileToDocument`'s `documents` output (the converter for text files) to `DocumentSplitter`'s `documents` input. 3. Reconnect `PPTXToDocument`'s `documents` output to `DocumentSplitter`'s `documents` input. 4. Reconnect `PDFMinerToDocument`'s `documents` output to `DocumentSplitter`'s `documents` input. 5. Reconnect another `TextFileToDocument`'s `documents` output (the converter for Markdown files) to `DocumentSplitter`'s `documents` input. 6. Reconnect `HTMLToDocument`'s `documents` output to `DocumentSplitter`'s `documents` input. 7. Reconnect `DOCXToDocument`'s `documents` output to `DocumentSplitter`'s `documents` input. 8. Remove the second `DocumentJoiner` component that collects documents from `CSVToDocument`, `XLSXToDocument`, and `DocumentSplitter`, and sends them to `DeepsetNvidiaDocumentEmbedder`. 9. Reconnect `DocumentSplitter`'s `documents` output to `DeepsetNvidiaDocumentEmbedder`'s `documents` input. 10. Reconnect `CSVToDocument`'s `documents` output to `DeepsetNvidiaDocumentEmbedder`'s `documents` input. 11. Reconnect `XLSXToDocument`'s `documents` output to `DeepsetNvidiaDocumentEmbedder`'s `documents` input.
Before: with DocumentJoiner ```yaml components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 HTMLToDocument: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true DOCXToDocument: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown PPTXToDocument: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} XLSXToDocument: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PDFMinerToDocument.sources - sender: FileTypeRouter.text/markdown receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/html receiver: HTMLToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: DOCXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: PPTXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: XLSXToDocument.sources - sender: FileTypeRouter.text/csv receiver: CSVToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: PDFMinerToDocument.documents receiver: DocumentJoiner.documents - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: HTMLToDocument.documents receiver: DocumentJoiner.documents - sender: DOCXToDocument.documents receiver: DocumentJoiner.documents - sender: PPTXToDocument.documents receiver: DocumentJoiner.documents - sender: XLSXToDocument.documents receiver: DocumentJoiner.documents - sender: CSVToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentJoiner.documents - sender: XLSXToDocument.documents receiver: DocumentJoiner.documents - sender: CSVToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DeepsetNvidiaDocumentEmbedder.documents - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - FileTypeRouter.sources max_runs_per_component: 100 metadata: {} ```
After: without DocumentJoiner ```yaml components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 HTMLToDocument: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true DOCXToDocument: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown PPTXToDocument: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} XLSXToDocument: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PDFMinerToDocument.sources - sender: FileTypeRouter.text/markdown receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/html receiver: HTMLToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: DOCXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: PPTXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: XLSXToDocument.sources - sender: FileTypeRouter.text/csv receiver: CSVToDocument.sources - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents - sender: PPTXToDocument.documents receiver: DocumentSplitter.documents - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: PDFMinerToDocument.documents receiver: DocumentSplitter.documents - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: HTMLToDocument.documents receiver: DocumentSplitter.documents - sender: DOCXToDocument.documents receiver: DocumentSplitter.documents inputs: files: - FileTypeRouter.sources max_runs_per_component: 100 metadata: {} ```
## Remove ListJoiner Components now accept multiple lists of the same type, which means you can get rid of `ListJoiner` in most cases. Below, you can find common use cases for `ListJoiner` and how to simplify them. ### Joining ChatMessages If you're joining multiple `list[ChatMessage]` using a `ListJoiner`, you can remove it. The pipeline now handles these conversions automatically. A common use case is joining messages from a [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx) with the current user's message to send them to the `Agent`, like in the RAG Research Agent template. You can now skip `ListJoiner` and connect the components directly. To do so, follow these steps: 1. Remove `ListJoiner`. 2. Connect [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx)'s `messages` output directly to the Agent's `messages` input. 3. Connect `ChatPromptBuilder`'s `prompt` output directly to the Agent's `messages` input.
Before: Joining ChatMessages with ListJoiner ```yaml components: adapter: init_parameters: custom_filters: {} output_type: list[str] template: '{{ [(messages|last).text] }}' unsafe: false type: haystack.components.converters.output_adapter.OutputAdapter history_parser: init_parameters: {} type: deepset_cloud_custom_nodes.parsers.chat_history_parser.DeepsetChatHistoryParser MultiFileConverter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: list[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: |- {% message role="user" %} {%- if documents|length > 0 -%} Here are documents provided by the user: {% for document in documents -%} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {%- endfor -%} {%- endif -%} {% endmessage %} ListJoiner: type: haystack.components.joiners.list_joiner.ListJoiner init_parameters: list_type_: list[haystack.dataclasses.chat_message.ChatMessage] Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.2 generation_kwargs: reasoning: effort: low verbosity: low type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator exit_conditions: - text max_agent_steps: 100 raise_on_tool_invocation_failure: false state_schema: documents: type: list[haystack.Document] streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback system_prompt: >- You are a deep research assistant. You create comprehensive research reports to answer the user's questions. You have one tool to gather data: 'local_search'. The local_search tool supports hybrid retrieval using keywords, semantic embeddings, and reranking. Formulate natural language search queries that describe the full intent of the question. Use multiple varied searches to fully cover the topic. Only information retrieved from local_search may be used to answer the question. If the question cannot be answered using this knowledge source, explicitly state that it is not answerable and briefly explain why. Do not use external knowledge, assumptions, or speculation. When you use information from the local search, cite the source with the documents reference number in square brackets where you use the information (e.g. [5]). This is IMPORTANT: - Only use numbered citations for the local search results. - Do NOT add a References section, cite directly in the text where you use the information. - For internal knowledge "some information" [3] as (taken from ). - Format responses using markdown. tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: local_search description: >- Search the company's internal knowledge repository using hybrid retrieval. The search supports natural language queries, keyword matching, semantic embeddings, and cross-encoder reranking. Use descriptive, question-like queries to capture intent and retrieve the most relevant documents. input_mapping: query: - retriever.query - ranker.query documents: - builder.existing_documents output_mapping: builder.prompt: formatted_docs meta_field_grouping_ranker.documents: documents inputs_from_state: documents: documents outputs_to_state: documents: source: documents outputs_to_string: source: formatted_docs parameters: is_pipeline_async: false pipeline: components: builder: init_parameters: required_variables: - existing_documents - docs template: |- {%- if existing_documents is not none -%} {%- set existing_doc_len = existing_documents|length -%} {%- else -%} {%- set existing_doc_len = 0 -%} {%- endif -%} {%- for doc in docs %} {{ doc.content }} {% endfor -%} variables: type: haystack.components.builders.prompt_builder.PromptBuilder retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: builder.docs max_runs_per_component: 100 metadata: {} DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0] }}" output_type: str custom_filters: unsafe: false connections: - sender: MultiFileConverter.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: ListJoiner.values - sender: history_parser.messages receiver: ListJoiner.values - sender: ListJoiner.values receiver: Agent.messages - sender: Agent.documents receiver: DeepsetAnswerBuilder.documents - sender: Agent.messages receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: DeepsetAnswerBuilder.replies inputs: query: - DeepsetAnswerBuilder.query - history_parser.history_and_query files: - MultiFileConverter.sources max_runs_per_component: 100 metadata: {} outputs: answers: DeepsetAnswerBuilder.answers documents: Agent.documents pipeline_output_type: chat ```
After: Joining ChatMessages without ListJoiner ```yaml components: adapter: init_parameters: custom_filters: {} output_type: list[str] template: '{{ [(messages|last).text] }}' unsafe: false type: haystack.components.converters.output_adapter.OutputAdapter history_parser: init_parameters: {} type: deepset_cloud_custom_nodes.parsers.chat_history_parser.DeepsetChatHistoryParser MultiFileConverter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: list[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: |- {% message role="user" %} {%- if documents|length > 0 -%} Here are documents provided by the user: {% for document in documents -%} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {%- endfor -%} {%- endif -%} {% endmessage %} Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.2 generation_kwargs: reasoning: effort: low verbosity: low type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator exit_conditions: - text max_agent_steps: 100 raise_on_tool_invocation_failure: false state_schema: documents: type: list[haystack.Document] streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback system_prompt: >- You are a deep research assistant. You create comprehensive research reports to answer the user's questions. You have one tool to gather data: 'local_search'. The local_search tool supports hybrid retrieval using keywords, semantic embeddings, and reranking. Formulate natural language search queries that describe the full intent of the question. Use multiple varied searches to fully cover the topic. Only information retrieved from local_search may be used to answer the question. If the question cannot be answered using this knowledge source, explicitly state that it is not answerable and briefly explain why. Do not use external knowledge, assumptions, or speculation. When you use information from the local search, cite the source with the documents reference number in square brackets where you use the information (e.g. [5]). This is IMPORTANT: - Only use numbered citations for the local search results. - Do NOT add a References section, cite directly in the text where you use the information. - For internal knowledge "some information" [3] as (taken from ). - Format responses using markdown. tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: local_search description: >- Search the company's internal knowledge repository using hybrid retrieval. The search supports natural language queries, keyword matching, semantic embeddings, and cross-encoder reranking. Use descriptive, question-like queries to capture intent and retrieve the most relevant documents. input_mapping: query: - retriever.query - ranker.query documents: - builder.existing_documents output_mapping: builder.prompt: formatted_docs meta_field_grouping_ranker.documents: documents inputs_from_state: documents: documents outputs_to_state: documents: source: documents outputs_to_string: source: formatted_docs parameters: is_pipeline_async: false pipeline: components: builder: init_parameters: required_variables: - existing_documents - docs template: |- {%- if existing_documents is not none -%} {%- set existing_doc_len = existing_documents|length -%} {%- else -%} {%- set existing_doc_len = 0 -%} {%- endif -%} {%- for doc in docs %} {{ doc.content }} {% endfor -%} variables: type: haystack.components.builders.prompt_builder.PromptBuilder retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: builder.docs max_runs_per_component: 100 metadata: {} DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0] }}" output_type: str custom_filters: unsafe: false connections: - sender: MultiFileConverter.documents receiver: ChatPromptBuilder.documents - sender: Agent.documents receiver: DeepsetAnswerBuilder.documents - sender: Agent.messages receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: DeepsetAnswerBuilder.replies - sender: history_parser.messages receiver: Agent.messages - sender: ChatPromptBuilder.prompt receiver: Agent.messages inputs: query: - DeepsetAnswerBuilder.query - history_parser.history_and_query files: - MultiFileConverter.sources max_runs_per_component: 100 metadata: {} outputs: answers: DeepsetAnswerBuilder.answers documents: Agent.documents pipeline_output_type: chat ```
## Remove OutputAdapter for Type Conversions ### RAG Chat with LLM sending input to a Retriever and a Ranker In chat pipelines, where the first LLM reformulates the query to be used for retrieval augmented generation, you can remove the `OutputAdapter` and connect the `ChatGenerator` directly to the `Retriever` or `Ranker`. This is an example of a RAG chat pipeline with an `OutputAdapter` and a `DocumentJoiner` that you can simplify. Follow these steps: 1. Remove `OutputAdapter`. 2. Connect the `replies` output of the first `OpenAIGenerator` to the following components' inputs: - `OpenSearchHybridRetriever`'s `query` input. - `DeepsetNvidiaRanker`'s `query` input. - `PromptBuilder`'s `question` input. - `DeepsetAnswerBuilder`'s `query` input. 3. Remove `DocumentJoiner`. 4. Connect `MultiFileConverter`'s `documents` output to the following components' inputs: - The second `PromptBuilder`'s `documents` input. - `DeepsetAnswerBuilder`'s `documents` input. - `Output`'s `documents` input. 5. Connect `DeepsetNvidiaRanker`'s `documents` output to the following components' inputs: - The second `PromptBuilder`'s `documents` input. - `DeepsetAnswerBuilder`'s `documents` input. - `Output`'s `documents` input.
Before: LLM connected to a Retriever through an OutputAdapter ```yaml components: PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: "type": "env_var" "env_vars": - "OPENAI_API_KEY" "strict": False model: "gpt-5.2" generation_kwargs: reasoning_effort: low verbosity: low OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0] }}" output_type: str OpenSearchHybridRetriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 DeepsetNvidiaRanker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: '*' template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: "type": "env_var" "env_vars": - "OPENAI_API_KEY" "strict": False model: "gpt-5.2" generation_kwargs: reasoning_effort: low verbosity: low DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true MultiFileConverter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: OpenSearchHybridRetriever.query - sender: OutputAdapter.output receiver: DeepsetNvidiaRanker.query - sender: OutputAdapter.output receiver: PromptBuilder.question - sender: OutputAdapter.output receiver: DeepsetAnswerBuilder.query - sender: retriever.documents receiver: DeepsetNvidiaRanker.documents - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: PromptBuilder.prompt receiver: DeepsetAnswerBuilder.prompt - sender: OpenAIGenerator.replies receiver: DeepsetAnswerBuilder.replies - sender: MultiFileConverter.documents receiver: DocumentJoiner.documents - sender: DeepsetNvidiaRanker.documents receiver: attachments_joiner.documents - sender: DocumentJoiner.documents receiver: DeepsetAnswerBuilder.documents - sender: DocumentJoiner.documents receiver: PromptBuilder.documents inputs: query: - PromptBuilder.question filters: - OpenSearchHybridRetriever.filters_bm25 - OpenSearchHybridRetriever.filters_embedding files: - MultiFileConverter.sources outputs: documents: DocumentJoiner.documents answers: DeepsetAnswerBuilder.answers max_runs_per_component: 100 metadata: {} ```
After: LLM connected directly to a Retriever and a Ranker This is a simplified version of the pipeline above. You can remove the `DocumentJoiner` and `OutputAdapter`and connect the components directly. ```yaml components: PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: "type": "env_var" "env_vars": - "OPENAI_API_KEY" "strict": False model: "gpt-5.2" generation_kwargs: reasoning_effort: low verbosity: low OpenSearchHybridRetriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 DeepsetNvidiaRanker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: '*' template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: "type": "env_var" "env_vars": - "OPENAI_API_KEY" "strict": False model: "gpt-5.2" generation_kwargs: reasoning_effort: low verbosity: low DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm MultiFileConverter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenSearchHybridRetriever.documents receiver: DeepsetNvidiaRanker.documents - sender: PromptBuilder.prompt receiver: DeepsetAnswerBuilder.prompt - sender: OpenAIGenerator.replies receiver: DeepsetAnswerBuilder.replies - sender: DeepsetNvidiaRanker.documents receiver: PromptBuilder.documents - sender: DeepsetNvidiaRanker.documents receiver: DeepsetAnswerBuilder.documents - sender: OpenAIGenerator.replies receiver: DeepsetNvidiaRanker.query - sender: OpenAIGenerator.replies receiver: DeepsetAnswerBuilder.query - sender: MultiFileConverter.documents receiver: DeepsetAnswerBuilder.documents - sender: MultiFileConverter.documents receiver: PromptBuilder.documents - sender: MultiFileConverter.documents receiver: Output.documents inputs: query: - PromptBuilder.question filters: - OpenSearchHybridRetriever.filters_bm25 - OpenSearchHybridRetriever.filters_embedding files: - MultiFileConverter.sources outputs: answers: DeepsetAnswerBuilder.answers max_runs_per_component: 100 metadata: {} ```
### When You Still Need OutputAdapter You still need `OutputAdapter` when: - You're converting between types that smart connections don't support (anything other than `string` and `ChatMessage`). - You need explicit control over formatting, ordering, or extracting specific fields from the output. ## Remove DeepsetChatHistoryParser [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx) was most commonly used with the `Agent` component to pass messages augmented with chat history to the `Agent`. Currently, this is done automatically. You can connect the `Input` component's `messages` output directly to the `Agent`'s `messages` input. `messages` include prior conversations from the search history. To simplify pipelines that contain [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx): 1. Delete [DeepsetChatHistoryParser](/docs/reference/pipeline-components/legacy-components/DeepsetChatHistoryParser.mdx) from your pipeline. 2. On the `Input` component card, click **Configure** and `-messages` as a connection point. 3. Connect the `Input` component's `messages` output to the `Agent`'s `messages` input. That's it. Your `Agent` will now receive messages augmented with chat history. --- ## Troubleshoot Pipelines and Indexes Diagnose and resolve common issues with pipelines and indexes. *** ## Pipeline Issues When creating or updating a pipeline, you may see validation errors that prevent deployment. Here are common errors and how to resolve them. :::tip Find and Fix Issues Faster Use the global Issues panel in Builder. You can find it at the bottom of the canvas. Expand the panel to view all validation and runtime issues in one place. Click **Inspect** next to any issue to jump directly to the affected component or connection. Click **Fix with AI** to open the AI assistant, which reasons through the fix and can apply it for you. ::: ### Unconnected Model Provider **Symptoms:** The Issues panel in Pipeline Builder shows a model connection issue for an LLM or Agent component. **What happens:** When a component such as `LLM` or `Agent` is configured to use a model provider that isn't connected to Haystack Enterprise Platform, an issue appears in the Issues panel. The issue shows the name of the affected model and provider. Components that use an embedded chat generator — such as `LLMMetadataExtractor` — are also checked for model connection status. If the configured provider is not connected, the Issues panel shows a warning for that component as well. **Solution:** 1. Open your pipeline in Pipeline Builder. 2. At the bottom of Builder, click **Issues** to open the Issues panel. 3. Find the model connection issue and click **Connect** next to it. 4. Enter your API key and any other required details for the provider. 5. Click **Connect** to save the integration. The issue disappears once the provider is connected. For general information on connecting model providers, see [Connect to Model and Service Providers](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx). ### Invalid Amazon Bedrock Model Identifier **Symptoms:** Your pipeline returns an error similar to: "The provided model identifier is invalid." **What happens:** Amazon Bedrock model IDs include a regional prefix (for example, `us.`, `eu.`, `ap.`) that must match the AWS region where your pipeline is deployed. If you configure a model ID with the wrong regional prefix — for example, using `us.anthropic.claude-haiku-4-5-20251001-v1:0` in a deployment region that requires the `eu.` prefix — AWS returns a validation error (HTTP 400 ValidationException). **Solution:** 1. Open your pipeline in Pipeline Builder and find the component that uses the Amazon Bedrock model. 2. Check the model ID configured in the component's settings. 3. Update the model ID to use the correct regional prefix for your deployment region. For example: - Use `eu.anthropic.claude-...` for deployments in European regions. - Use `us.anthropic.claude-...` for deployments in US regions. - Use `ap.anthropic.claude-...` for deployments in Asia Pacific regions. 4. For a full list of model IDs and supported regions, see [Amazon Bedrock model IDs](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html). 5. Redeploy your pipeline. For more information on setting up Amazon Bedrock models, see [Use Amazon Bedrock Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx). ### Invalid Streaming Component Error If your pipeline contains components that don't support streaming, this error is shown: **Error message**: "Invalid streaming component - This pipeline contains a component that does not support streaming. Remove or replace the incompatible component to enable streaming." **Solution**: To resolve this error: 1. Identify which components in your pipeline don't support streaming. 2. Either remove the incompatible component or replace it with a streaming-compatible alternative. 3. For more information about streaming and compatible components, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). ### OpenSearch Filter Missing Operator **Symptoms:** Your pipeline returns an error like `FilterError: 'operator' key missing` when running a query with filters against an OpenSearch retriever. **What happens:** OpenSearch retrievers such as `OpenSearchBM25Retriever` and `OpenSearchHybridRetriever` require filters to follow a structured format with three keys: `field`, `operator`, and `value`. Passing a flat dict — for example, `{'year': 2024}` — raises this error because the required `operator` key is missing. **Solution:** Update your filter to use the correct structured format: ```json { "field": "year", "operator": "==", "value": 2024 } ``` For combining multiple conditions, use a logical operator with a `conditions` list: ```json { "operator": "AND", "conditions": [ {"field": "year", "operator": ">=", "value": 2020}, {"field": "category", "operator": "==", "value": "news"} ] } ``` ### Pipeline Builder Canvas Fails to Load **Symptoms:** Instead of the visual canvas, Pipeline Builder shows an error message with **Retry** and **Switch to YAML** buttons. **What happens:** Pipeline Builder requires several resources to render the visual canvas correctly — including component definitions, input/output metadata, and visualization data for your pipeline. If any of these fail to load, Builder shows an error state rather than an empty or broken canvas. This prevents you from accidentally working with an incomplete graph. **What you can do:** - **Retry**: Click **Retry** to reload the failed resources. Builder automatically retries a few times when a resource fails; the **Retry** button lets you trigger this manually after the automatic retries are exhausted. - **Switch to YAML**: Click **Switch to YAML** to open the YAML editor. The YAML editor does not depend on the visual canvas resources, so you can still view and edit your pipeline configuration while the issue resolves. :::info Your pipeline is safe Your pipeline is not affected by this error. The YAML configuration — the source of truth for your pipeline — remains intact. Autosave and manual save are paused while the canvas is in this state to prevent incomplete data from being saved. ::: **If the error persists:** 1. Refresh the page and reopen the pipeline. 2. Check your network connection and verify there are no connectivity issues. 3. If the problem continues, contact deepset support. ### Pipeline Stuck in Deploying **Symptoms:** The pipeline status shows _deploying_ for an extended period of time and does not change. **What happens:** The platform automatically detects pipelines that have been deploying longer than expected and marks them as _failed to deploy_. This usually happens within a few minutes. Once the status changes to _failed to deploy_, you can redeploy the pipeline. **Solution:** 1. Wait a few minutes for the platform to detect the stuck deployment and update the status to _failed to deploy_. 2. Once the status has changed, redeploy the pipeline. For details, see [Deploy a Pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx). 3. If the pipeline fails to deploy again, check the pipeline YAML for configuration errors. ### Pipeline Performance Issues **Symptoms:** Pipeline is slow or times out. **Possible causes and solutions:** - Model latency: Try switching to a faster model or enable GPU acceleration. For details, see [Enable GPU Acceleration for Pipelines](/docs/how-to-guides/designing-your-pipeline/set-additional-params/enable-gpu.mdx). - Network bottlenecks: Check connectivity to external services and document stores. ## Index Issues ### Index Status: Partially Indexed - **Symptoms:** All of the files were processed, but at least one of the files failed to be indexed. - **Possible causes and solutions:** - Missing dependencies: Ensure all required components and integrations are properly configured. If you're unsure about whether a component is correctly configured, you can run it in isolation to see if it works. For details, see [Run Components and Pipelines in Builder](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). - Invalid YAML configuration: Check your pipeline YAML for syntax errors. - Corrupted files: Check if you your files are OK. You can use the [get indexed files by status](/docs/api/main/get-indexed-files-by-status-api-v-1-workspaces-workspace-name-indexes-index-name-files-get.api.mdx) endpoint to see the status of the files. - Retry indexing: Reindex the failed files: 1. Go to *Indexes* and click the index that you're troubleshooting. This opens the Files page. 2. Click **More Actions** next to a failed file and choose **Retry Indexing**. ### Indexing Performance Issues **Symptoms:** Indexing is slow or search results are poor. **Possible causes and solutions:** - Document preprocessing: Optimize document splitting and cleaning strategies. - Embedding model choice: Consider choosing different embedding models for your content. - Index settings: Adjust document store settings for better performance. ## Debugging Tools For details on how to debug your pipelines, see [Debugging Pipelines](/docs/how-to-guides/productionizing-your-pipeline/trace-your-pipelines.mdx). --- ## Using Hosted Models and External Services is integrated with multiple model and service providers. Learn how to benefit from it in your pipelines. *** :::info Need a custom integration? To use a third-party provider or service that’s not listed in Integrations, you can create a custom component to connect to it. For details, see [Create a Custom Component](../work-with-custom-components/create-a-custom-component.mdx). ::: ## Accessing Integrations All integrations are listed on the Integrations page in Settings. To access settings, click your profile icon and choose *Settings*: - To see workspace-level integrations, go to *Workspace>Integrations*. - To see organization-level integrations, go to *Organization>Integrations*. For more information about integrations and their scope, see [Secrets and Integrations](/docs/concepts/secrets-and-integrations.mdx) and [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). ## Supported Providers ## Adding Custom Models Add custom model definitions at the organization or workspace level. After you save a definition, you can reuse it in your pipeline components. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ## Adding Integrations to Your Pipeline 1. Add the provider's API key on the *Integrations* page. 2. Add a component that supports the integration to your pipeline. Find the integration you want to use and follow the detailed steps below: - [Use Amazon Bedrock and SageMaker Models](./using-amazon-bedrock-models.mdx) - [Use Azure Document Intelligence](/docs/how-to-guides/working-with-indexes/use-azure-document-intelligence.mdx) - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Use Cohere Models](./use-cohere-models.mdx) - [Use DeepL Translation Services](./use-deepl-translation-services.mdx) - [Use Google Gemini Models](./use-googleai-models.mdx) - [Use Google Search API](./use-google-search-api.mdx) - [Use Hugging Face Models](./use-hugging-face-models.mdx) - [Use NVIDIA Models](./use-nvidia-models.mdx) - [Use OpenAI Models](./use-openai-models.mdx) - [Use Snowflake Database](/docs/how-to-guides/working-with-your-data/use-snowflake-database.mdx) - [Use Together AI Models](./use-togetherai-models.mdx) - [Use https://unstructured.io/ to Process Documents](/docs/how-to-guides/working-with-indexes/use-unstructured.mdx) - [Use Voyage AI Models](./use-voyage-ai.mdx) - [Use Weights & Biases Services](/docs/how-to-guides/productionizing-your-pipeline/use-weights-and-biases.mdx) ## Integrations with Secrets There are also other model providers and frameworks you can use in your pipelines, even though they're not listed on the *Integrations* page. To use these integrations, add a secret on the *Secrets* page and then pass the secret name as the API key required by the provider. For details, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). --- ## Use Anthropic Models Use Anthropic models through Anthropic API in your pipelines. *** You can use Anthropic's embedding and ranking models as well as LLMs. For a full list of supported models, see [Anthropic documentation](https://docs.anthropic.com/en/docs/about-claude/models). ## Prerequisites You need an active Anthropic API key to use Anthropic's models. ## Use Anthropic Models First, connect to Anthropic through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses an Anthropic model to your pipeline. Here are the available components: - [AnthropicVertexChatGenerator](/docs/reference/pipeline-components/integrations/google-vertex/AnthropicVertexChatGenerator.mdx): Generates text using Anthropic models on Google Vertex. - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx): Generates text using Anthropic models. :::info Legacy The previously used `AnthropicChatGenerator` and `AnthropicGenerator` are now legacy components. Use the `LLM` component instead. ::: Click the component card to open the configuration panel and choose the model and other settings. ## Use Anthropic Models on Azure To use Anthropic models on Azure, create a custom model definition and choose *Anthropic on Azure* as the model provider: 1. Depending on the scope of the custom model definition: - For a workspace-wide custom model definition, go to _Workspace>Integrations_ and click **Configure** on the Custom Models Card. - For an organization-wide custom model definition, go to _Organization>Integrations_ and click **Configure** on the Custom Models Card. 2. Click **Add model**. 3. Enter the following details: - *Model name*: A descriptive name for your custom model - *Provider*: Choose *Anthropic on Azure*. 4. Configure the YAML settings: - Chat Generator: Define the component configuration including the endpoint or resource, and model name. - Model Parameters: Specify model parameters, like temperature and max output tokens. You can choose a model to copy its default parameters and adjust them as needed. 6. Save your changes. The model is now available in the model list when you add an Anthropic component to your pipeline. ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Cohere Models Use Cohere models through Cohere API in your pipelines. *** You can use Cohere's embedding and ranking models as well as LLMs. For a full list of supported models, see [Cohere documentation](https://docs.cohere.com/docs/models). ## Prerequisites You need an active Cohere API key to use Cohere's models. ## Use Cohere Models First, connect to Cohere through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a Cohere model to your pipeline. Here are the components by the model type they use: - Embedding models: - [`CohereTextEmbedder`](/docs/reference/pipeline-components/integrations/cohere/CohereTextEmbedder.mdx): Calculates embeddings for text, like query. Often used in query pipelines to embed a query and pass the embedding to an embedding retriever. - [`CohereDocumentEmbedder`](/docs/reference/pipeline-components/integrations/cohere/CohereDocumentEmbedder.mdx): Calculates embeddings for documents. Often used in indexes to embed documents and pass them to `DocumentWriter`. - LLMs: - [`CohereGenerator`](/docs/reference/pipeline-components/integrations/cohere/CohereGenerator.mdx): Generates text using a Cohere model, often used in RAG pipelines. - Ranking models: - [`CohereRanker`](/docs/reference/pipeline-components/integrations/cohere/CohereRanker.mdx): Ranks documents based on their similarity to the query. Often used in query pipelines to rank documents from the retriever and pass them on to `PromptBuilder`. ## Usage Examples This is an example of how to use Cohere's embedding and ranking models and an LLM in an index and a query pipeline (each in a separate tab): ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack_integrations.components.embedders.cohere.document_embedder.CohereDocumentEmbedder init_parameters: model: embed-english-v3.0 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ```yaml Query Pipeline components: # ... query_embedder: type: haystack_integrations.components.embedders.cohere.text_embedder.CohereTextEmbedder init_parameters: model: embed-english-v3.0 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 ranker: type: haystack_integrations.components.rankers.cohere.ranker.CohereRanker init_parameters: model: rerank-english-v3.0 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: generator: type: haystack_integrations.components.generators.cohere.generator.CohereGenerator init_parameters: generation_kwargs: temperature: 0.0 model: command answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # Defines how the components are connected # ... - sender: query_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies inputs: query: # ... - "query_embedder.text" # TextEmbedder needs query as input and it's not getting it - "retriever.query" # from any component it's connected to, so it needs to receive it from the pipeline. - "prompt_builder.question" - "answer_builder.query" - "ranker.query" ``` --- ## Use DeepL Translation Services Translate your documents using DeepL services. *** ## Prerequisites You need an active DeepL account and a DeepL API key. For guidance on how to obtain it, see [API Key for DeepL's API](https://support.deepl.com/hc/en-us/articles/360020695820-API-Key-for-DeepL-s-API). ## Use DeepL First, connect to DeepL through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a DeepL model to your pipeline. Available components: - [`DeepsetDeepLDocumentTranslator`](/docs/reference/pipeline-components/integrations/deepl/DeepsetDeepLDocumentTranslator.mdx): Translates documents using DeepL services. - [`DeepsetDeepLTextTranslator`](/docs/reference/pipeline-components/integrations/deepl/DeepsetDeepLTextTranslator.mdx): Translates text using DeepL services. ## Usage Examples This is an example of how to use DeepL in your pipeline. You connect the DeepL translator's input to a component that outputs documents like a `Ranker`. Then, you connect the translated documents to the `Output` component so that the pipeline can return the documents as an answer. This is the YAML configuration: ```yaml # haystack-pipeline components: query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: "intfloat/multilingual-e5-base" device: null embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 # The number of results to return ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "jeffwan/mmarco-mMiniLMv2-L12-H384-v1" top_k: 20 device: null model_kwargs: torch_dtype: "torch.float16" deepl_translator: type: deepl_haystack.components.DeepLDocumentTranslator # For more information about DeepL supported languages, see https://developers.deepl.com/docs/resources/supported-languages init_parameters: api_key: {"type": "env_var", "env_vars": ["DEEPL_API_KEY"], "strict": False} target_lang: ["DE"] # Translate documents into German source_lang: null # Auto-detects the source language when set to "null" preserve_formatting: true # Prevent automatic correction of formatting connections: # Defines how the components are connected - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: deepl_translator.documents max_loops_allowed: 100 inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "query_embedder.text" - "ranker.query" filters: # These components will receive a potential query filter as input - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "deepl_translator.translated_documents" # The output of the pipeline is the retrieved documents translated into German. ``` You configure the target languages as a list: ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Google Search API Add a web search to your pipelines using Google Search API. *** You can add a search engine that uses [Google's Search API](https://www.searchapi.io/) to your pipelines. ## Prerequisites You need an API key from Google Search API. ## Use Search API First, connect to SearchApi through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add the `SearchApiWebSearch` component to your pipeline. This component uses page snippets to find relevant pages and returns a list of URLs. It's typically used before a `LinkContentFetcher` or `Converters`. ## Usage Examples This is an example of a pipeline that uses SearchApi: ```yaml components: # ... web_retriever: type: haystack.components.websearch.searchapi.SearchApiWebSearch init_parameters: top_k: 20 link_fetcher: type: haystack.components.fetchers.link_content.LinkContentFetcher init_parameters: {} # we're leaving the default value parameters html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: txt # Extract text from HTML. You can also also choose "markdown" target_language: null # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: false # If true, keeps links along with their targets connections: # ... - sender: web_retriever.links receiver: link_fetcher.urls - sender: link_fetcher.urls receiver: html_converter.sources inputs: query: - "web_retriever.query" ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Google AI Models Use the multimodal Gemini models in your pipelines through Gemini API. *** ## Prerequisites You need an active Google AI Studio API key to use Gemini models. ## Use Gemini Models First, connect to GoogleAI through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a Gemini LLM to your pipeline: - LLMs: - [`LLM`](/docs/reference/pipeline-components/ai/LLM.mdx): Can generate text using a Gemini model, that's the easiest way to use a Gemini model in your pipeline. - [`GoogleGenAIChatGenerator`](/docs/reference/pipeline-components/integrations/google-ai/GoogleGenAIChatGenerator.mdx): Can generate text using a Gemini model. - Embedding models: - [`GoogleGenAITextEmbedder`](/docs/reference/pipeline-components/integrations/google-ai/GoogleGenAITextEmbedder.mdx): Calculates embeddings for text, like query. Often used in query pipelines to embed a query and pass the embedding to an embedding retriever. - [`GoogleGenAIDocumentEmbedder`](/docs/reference/pipeline-components/integrations/google-ai/GoogleGenAIDocumentEmbedder.mdx): Calculates embeddings for documents. Often used in indexes to embed documents and pass them to `DocumentWriter`. ## Usage Examples This is an example of how to use `GoogleGenAIChatGenerator` in a query pipeline: ```yaml # haystack-pipeline components: GoogleGenAIChatGenerator: type: haystack_integrations.components.generators.google_genai.chat.chat_generator.GoogleGenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini vertex_ai_project: vertex_ai_location: model: gemini-2.5-flash generation_kwargs: safety_settings: streaming_callback: tools: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: > - _content: - text: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ query }} _role: user required_variables: variables: inputs: query: - ChatPromptBuilder.query filters: [] files: [] messages: [] outputs: answers: documents: messages: GoogleGenAIChatGenerator.replies connections: - sender: ChatPromptBuilder.prompt receiver: GoogleGenAIChatGenerator.messages ``` --- ## Use Hugging Face Models Use models hosted on Hugging Face in your pipelines. *** ## About This Task You can use any model from Hugging Face in your pipelines. There are a couple of ways to do it: - You can download a model from Hugging Face and then pass its location to the pipeline component that uses it. - You can use one of Hugging Face's APIs: - [Free Serverless Inference API](https://huggingface.co/inference-api/serverless) - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints/dedicated) - [Self-hosted Text Embedding Inference](https://github.com/huggingface/text-embeddings-inference) ## Prerequisites You need a Hugging Face token for the API you want to use. ## Use Models from Hugging Face Connect to Hugging Face through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses the model you have in mind. Here are the available components by the model type: - Embedding models: - [`HuggingFaceAPIDocumentEmbedder`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPIDocumentEmbedder.mdx): Computes document embeddings using Hugging Face's APIs. - [`HuggingFaceAPITextEmbedder`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPITextEmbedder.mdx): Computes text embeddings using Hugging Face's APIs. - [`SentenceTransformersDocumentEmbedder`](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersDocumentEmbedder.mdx): Embeds documents using Sentence Transformers models. You can use it through Hugging Face's APIs. - [`SentenceTransformersTextEmbedder`](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersTextEmbedder.mdx): Embeds text using Sentence Transformers models. You can use it through Hugging Face's APIs. - [`SentenceTransformersSparseDocumentEmbedder`](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersSparseDocumentEmbedder.mdx): Embeds documents using Sentence Transformers models. You can use it through Hugging Face's APIs. - [`SentenceTransformersSparseTextEmbedder`](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersSparseTextEmbedder.mdx): Embeds text using Sentence Transformers models. You can use it through Hugging Face's APIs. - Named entity extraction: - [`NamedEntityExtractor`](/docs/reference/pipeline-components/data-processing/extract/NamedEntityExtractor.mdx): Can work with Hugging Face models if you set its `backend` parameter to `hugging_face`. - LLMs: - [`HuggingFaceAPIChatGenerator`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPIChatGenerator.mdx): Completes chats using Hugging Face APIs. - [`HuggingFaceAPIGenerator`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPIGenerator.mdx): Uses text-generating models through Hugging Face APIs. - [`HuggingFaceLocalChatGenerator`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceLocalChatGenerator.mdx): Uses a Hugging Face chat-completion model that runs locally. - Ranking models: - [`HuggingFaceTEIRanker`](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceTEIRanker.mdx): Uses a cross-encoder model to rank documents. You can use models through Hugging Face APIs. - Readers: - [`ExtractiveReader`](/docs/reference/pipeline-components/ai/ExtractiveReader.mdx): Extracts answers from the text. - Routers: - [`TransformersTextRouter`](/docs/reference/pipeline-components/logic-and-flow/TransformersTextRouter.mdx): Routes text to various outputs based on a categorization label provided by the model it uses. ## Usage Examples Check the documentation of the component you want to use for usage examples. ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) --- ## Use NVIDIA Models Use models from NVIDIA in your pipelines. *** ## About This Task You can use self-hosted models from the[ NVIDIA API catalog](https://docs.api.nvidia.com/nim/reference/models-1) or models deployed on NVIDIA NIM. ## Prerequisites You need an active NVIDIA API key. For details on how to obtain it, see [NVIDIA documentation](https://org.ngc.nvidia.com/setup/personal-keys). ## Use NVIDIA Models First, connect to NVIDIA through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a model hosted on NVIDIA to your pipeline. Here are the components by the model type they use: - Embedding models: - [`NvidiaTextEmbedder`](/docs/reference/pipeline-components/integrations/nvidia/NvidiaTextEmbedder.mdx): Uses an embedding model to calculate vector representations of text. Often used in query pipelines to embed the query string and send it to an embedding retriever. - [`NvidiaDocumentEmbedder`](/docs/reference/pipeline-components/integrations/nvidia/NvidiaDocumentEmbedder.mdx): Uses an embedding model to calculate embeddings of documents. Often used in indexes to embed documents and send them to DocumentWriter. - LLMs: - [`NvidiaChatGenerator`](/docs/reference/pipeline-components/integrations/nvidia/NvidiaChatGenerator.mdx): Generates text using models from NVIDIA. Often used in RAG pipelines. - Ranking models: - [`NvidiaRanker`](/docs/reference/pipeline-components/integrations/nvidia/NvidiaRanker.mdx): Ranks documents based on their similarity to the query using NVIDIA ranking models. ## Usage Examples This is a YAML example of how to use embedding models and an LLM hosted on NVIDIA in an index and a query pipeline (each in a separate tab): ```yaml Pipeline # haystack-pipeline components: # ... query_embedder: type: haystack_integrations.components.embedders.nvidia.text_embedder.NvidiaTextEmbedder init_parameters: api_url: "https://ai.api.nvidia.com/v1/retrieval/nvidia" # custom API URL for NVIDIA NIM. model: "NV-Embed-QA" # the model to use retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: > - _content: - text: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ query }} _role: user required_variables: variables: generator: type: haystack_integrations.components.generators.nvidia.chat.chat_generator.NvidiaChatGenerator init_parameters: model: "meta/llama3-70b-instruct" # here, pass the name of the model to use api_base_url: "https://integrate.api.nvidia.com/v1" generation_kwargs: temperature: 0.2 top_p: 0.7 max_tokens: 1024 output_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # ... - sender: query_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.messages - sender: generator.replies receiver: output_adapter.replies - sender: output_adapter.output receiver: answer_builder.replies ``` ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack_integrations.components.embedders.nvidia.document_embedder.NvidiaDocumentEmbedder init_parameters: api_url: "https://ai.api.nvidia.com/v1/retrieval/nvidia" # A required custom NVIDIA API URL for NVIDIA NIM model: "NV-Embed-QA" # the model to use writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use OpenAI Models Use OpenAI models in your pipelines. *** ## About This Task You can use OpenAI's embedding models and LLMs: - For a list of embedding models, see [OpenAI documentation](https://platform.openai.com/docs/guides/embeddings/embedding-models). - For a list of LLMs, see [OpenAI model overview](https://platform.openai.com/docs/models/models-overview). ## Prerequisites You need an API key from an active OpenAI account. For details on obtaining it, see [Secret keys in OpenAI](https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key). ## Use OpenAI Models First, connect to OpenAI through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses an OpenAI model to your pipeline. Here are the components by the model type they use: - Embedding models: - [`OpenAITextEmbedder`](/docs/reference/pipeline-components/integrations/openai/OpenAITextEmbedder.mdx): Calculates embeddings for text, like query. Often used in query pipelines to embed a query and pass the embedding to an embedding retriever. - [`OpenAIDocumentEmbedder`](/docs/reference/pipeline-components/integrations/openai/OpenAIDocumentEmbedder.mdx): Calculates embeddings for documents. Often used in indexes to embed documents and pass them to `DocumentWriter`. - LLMs: - [`OpenAIChatGenerator`](/docs/reference/pipeline-components/legacy-components/OpenAIChatGenerator.mdx): Generates text using OpenAI models, often used in RAG pipelines. - [`LLM`](/docs/reference/pipeline-components/ai/LLM.mdx): Generates text using OpenAI models, often used in RAG pipelines. ## Available OpenAI LLMs The following OpenAI LLMs are available in : | Model | Description | |-------|-------------| | GPT-5.6 Sol | Latest GPT-5.6 variant with `reasoning_effort` and `reasoning_summary` parameters. | | GPT-5.6 Terra | Latest GPT-5.6 variant with `reasoning_effort` and `reasoning_summary` parameters. | | GPT-5.6 Luna | Latest GPT-5.6 variant with `reasoning_effort` and `reasoning_summary` parameters. | | GPT-5.5 | GPT-5.5 with `reasoning_effort` and `reasoning_summary` parameters. | | GPT-5.5 Pro | GPT-5.5 Pro variant. | | GPT-5.4 | GPT-5.4 model. | | GPT-5.4 Pro | GPT-5.4 Pro variant. | | GPT-5.4 mini | Smaller, faster GPT-5.4 variant. | | GPT-5.4 nano | Compact GPT-5.4 variant. | | GPT-5.2 | GPT-5.2 model. | | GPT-5.2 Pro | GPT-5.2 Pro variant (no text-to-speech support). | | GPT-5.1 | GPT-5.1 model. | | GPT-5 | GPT-5 base model. | | GPT-5 Pro | GPT-5 Pro variant. | | GPT-5 mini | Smaller, faster GPT-5 variant. | | GPT-5 nano | Compact GPT-5 variant. | | GPT-4.1 | GPT-4.1 model. | | GPT-4.1 mini | Smaller GPT-4.1 variant. | | GPT-4.1 nano | Compact GPT-4.1 variant. | | GPT-4o | GPT-4o model. | | GPT-4o mini | Smaller GPT-4o variant. | | GPT-3.5 Turbo | GPT-3.5 Turbo model. | ## Usage Examples This is an example of how to use OpenAI's embedding models and an LLM in an index and a query pipeline (each in a separate tab): ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder init_parameters: model: text-embedding-ada-002 # the model to use writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ```yaml Query Pipeline # haystack-pipeline pipeline_output_type: "chat" components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: Standard-Index-English max_chunk_bytes: 104857600 return_embedding: false create_index: true settings: index.knn: true top_k: 20 # The number of results to return embedder: type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder init_parameters: model: text-embedding-ada-002 fuzziness: 0 ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 device: null meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id qa_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: # You can swap this for any other model. Switch to the Builder view and choose another model from the list on the component card. chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {% for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor %} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question.text }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: qa_llm.documents inputs: filters: - retriever.filters_bm25 - retriever.filters_embedding files: [] query: - qa_llm.question - ranker.query - retriever.query outputs: documents: meta_field_grouping_ranker.documents messages: qa_llm.messages updated_query: max_runs_per_component: 100 metadata: {} ``` Here is how to connect the components in Pipeline Builder. In the index, `OpenAIDocumentEmbedder` receives documents from `DocumentSplitter` and then passes the embedded documents to `DocumentWriter`, which writes them into the Document Store: In a query pipeline, `OpenAITextEmbedder` embeds the query using the same model as the `OpenAIDocumentEmbedder` in the index. Then, it sends the embedded query to the retriever, which fetches matching documents and sends them to `PromptBuilder`. `OpenAIGenerator` then receives the rendered prompt from the `PromptBuilder` and sends the generated replies to `AnswerBuilder` to build a proper `GeneratedAnswer` object. ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Together AI Models Use models, such as DeepSeek-R1, hosted on Together AI. *** ## About This Task You can use models hosted on Together AI in your pipelines. For a complete list of models, see the _Inference_ section of [Together AI documentation](https://docs.together.ai/docs/serverless-models). ## Prerequisites You need an API key from an active Together AI account. For details on obtaining it, see [Together AI Quickstart](https://docs.together.ai/docs/quickstart). ## Use Models Hosted on Together AI First, connect to Together AI through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a model hosted on Together AI to your pipeline. Here are the components by the model type they use: - LLMs: - [`TogetherAIChatGenerator`](/docs/reference/pipeline-components/integrations/togetherai/TogetherAIChatGenerator.mdx): Generates text using models hosted on Together AI. - [`TogetherAIGenerator`](/docs/reference/pipeline-components/integrations/togetherai/TogetherAIGenerator.mdx): Generates text using models hosted on Together AI. ## Usage Examples This is an example of a RAG pipeline that uses the DeepSeek-R1 model hosted on Together AI: ```yaml components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: llm: type: haystack_integrations.components.generators.togetherai.generator.TogetherAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["TOGETHER_API_KEY"], "strict": false} model: deepseek-ai/DeepSeek-R1 generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: # Defines how the components are connected - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: llm.replies receiver: answer_builder.replies - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: prompt_builder.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" files: - multi_file_converter.sources outputs: # Defines the output of your pipeline documents: "attachments_joiner.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Voyage AI Models Create embeddings using top-performing embedding models by Voyage AI. *** ## About This Task :::info Third Party Integration Voyage AI is a third party integration developed by an external provider and is not maintained by . While we encourage you to explore it, we recommend reviewing it carefully to ensure it meets your needs. ::: Use Voyage AI models to calculate embeddings for documents and queries in your pipelines. For available models, see [Voyage AI documentation](https://docs.voyageai.com/docs/embeddings). ## Prerequisites You need an API key from Voyage AI. For details, see the [Voyage website](https://www.voyageai.com/). ## Use Voyage Models First, connect to Voyage AI through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses a Voyage model. The following components are available: - Embedding models: - [`VoyageTextEmbedder`](/docs/reference/pipeline-components/integrations/voyage/VoyageTextEmbedder.mdx): Embeds text strings. You can use it in a query pipeline to embed the query and pass it to an embedding retriever. - [`VoyageDocumentEmbedder`](/docs/reference/pipeline-components/integrations/voyage/VoyageDocumentEmbedder.mdx): Embeds documents. You can use it in indexes to calculate embeddings for documents. - Ranking models: - [`VoyageRanker`](/docs/reference/pipeline-components/integrations/voyage/VoyageRanker.mdx): Ranks documents based on their similarity to the query using Voyage AI ranking models. ## Usage Examples This is an example of an index and a query pipeline (each in a separate tab) that uses Voyage models to embed text (query pipeline) and documents (index): ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_document_embedder.VoyageDocumentEmbedder init_parameters: model: "voyage-2" # the model to use writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ```yaml components: # ... query_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_text_embedder.VoyageTextEmbedder init_parameters: model: "voyage-2" # the model to use retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: generator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-3.5-turbo" # the model to use generation_kwargs: # additional parameters for the model max_tokens: 400 temperature: 0.0 seed: 0 answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # Defines how the components are connected # ... - sender: query_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies inputs: query: # ... - "query_embedder.text" # TextEmbedder needs query as input and it's not getting it - "retriever.query" # from any component it's connected to, so it needs to receive it from the pipeline. - "prompt_builder.question" - "answer_builder.query" ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Use Amazon Bedrock Models You can use models hosted in your own Bedrock account. *** You can use embedding models and LLMs hosted on Amazon Bedrock through Bedrock's API. You can connect to your Bedrock account using your Bedrock API key of IAM access key. For a full list of supported models, see [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html). ## Bedrock Prompt Caching Amazon Bedrock models support prompt caching for system prompts. You can set the `system_cachepoint_config_ttl` for models hosted on Amazon Bedrock to cache your system prompt for 5 minutes (`"5m"`) or 1 hour (`"1h"`), reducing latency and cost for repeated requests that share the same system prompt. The system prompt must stay static, with no parameters, for the cache to work. ## Prerequisites - To connect using your Bedrock API key, you must have a valid API key. - To connect using your IAM access key, you must have a valid access key ID and secret access key for your Amazon region. For details, see [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) and [Amazon Bedrock documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/gs.html). ## Using Bedrock Models First, connect to Amazon Bedrock by passing your Bedrock API key or IAM access key on the Integrations page. You can do so for a single workspace or for the whole organization: Then, add a component that uses the Bedrock model to your pipeline. Here is a list of components by the model type they use: - Embedding models (used to calculate embeddings for text): - [`AmazonBedrockTextEmbedder`](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockTextEmbedder.mdx): Calculates embeddings for text, such as query. Often used in query pipelines to embed query and then pass it to an embedding retriever. - [`AmazonBedrockDocumentEmbedder`](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockDocumentEmbedder.mdx): Calculates embeddings for documents. Often used in indexes to embed documents and pass them to DocumentWriter. - LLMs: - [`LLM`](/docs/reference/pipeline-components/ai/LLM.mdx): Generates text, often used in RAG pipelines. - Rankers: - [`AmazonBedrockRanker`](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockRanker.mdx): Ranks documents based on their similarity to the query using Amazon Bedrock models. :::info Legacy The previously used `AmazonBedrockGenerator`, `AmazonBedrockChatGenerator`, `DeepsetAmazonBedrockGenerator`, and `DeepsetAmazonBedrockChatGenerator` are deprecated. Use the `LLM` component instead. ::: ### Usage Examples This is an example of how to use embedding models and an LLM hosted on Bedrock in an index and a query pipeline (each in a separate tab): ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack_integrations.components.embedders.amazon_bedrock.document_embedder.AmazonBedrockDocumentEmbedder init_parameters: model: "cohere.embed-english-v3" writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ```yaml # haystack-pipeline inputs: query: - AmazonBedrockTextEmbedder.text filters: [] files: [] messages: [] components: LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: global.anthropic.claude-sonnet-4-6 type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" streaming_callback: AmazonBedrockTextEmbedder: type: haystack_integrations.components.embedders.amazon_bedrock.text_embedder.AmazonBedrockTextEmbedder init_parameters: model: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true search_kwargs: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: "" max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false settings: index.knn: true create_index: true outputs: answers: documents: messages: LLM.messages connections: - sender: AmazonBedrockTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding - sender: OpenSearchEmbeddingRetriever.documents receiver: LLM.documents ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) --- ## Use Azure OpenAI Models Use OpenAI models deployed through Azure services in your pipelines. *** For a list of supported models, see [Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?source=recommendations). :::tip Anthropic on Azure For information on using Anthropic models on Azure, see [Use Anthropic Models on Azure](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx#use-anthropic-models-on-azure). ::: ## Prerequisites You need an Azure OpenAI API key and Azure OpenAI endpoint. For details, see [Azure REST API reference](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference). ## Use Azure OpenAI First, connect to Azure through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add a component that uses an OpenAI model through Azure to your pipeline. Here are the components by the model type they use: - Embedding models: - [`AzureOpenAITextEmbedder`](/docs/reference/pipeline-components/integrations/azure/AzureOpenAITextEmbedder.mdx): Calculates embeddings for text, like query. Often used in query pipelines to embed a query and pass the embedding to an embedding retriever. - [`AzureOpenAIDocumentEmbedder`](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIDocumentEmbedder.mdx): Calculates embeddings for documents. Often used in indexes to embed documents and pass them to DocumentWriter. - LLMs: - [`AzureOpenAIGenerator`](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIGenerator.mdx) - [`AzureOpenAIChatGenerator`](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIChatGenerator.mdx) - [`AzureOpenAIResponsesChatGenerator`](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIResponsesChatGenerator.mdx) ## Usage Examples This is an example of how to use embedding models and an LLM hosted on Azure in an index and a pipeline (each in a separate tab): ```yaml components: # ... splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder init_parameters: azure_deployment: "text-embedding-ada-002" # this is the name of the model you want to use writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected # ... - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents ``` ```yaml Query Pipeline components: # ... query_embedder: type: haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder init_parameters: azure_endpoint: "https://your-company.azure.openai.com/" azure_deployment: "text-embedding-ada-002" #this is the name of the model you want to use retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: generator: type: haystack.components.generators.azure.AzureOpenAIGenerator init_parameters: generation_kwargs: temperature: 0.0 azure_deployment: gpt-35-turbo #this is the model you want to use answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # Defines how the components are connected # ... - sender: query_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies inputs: query: # ... - "query_embedder.text" # TextEmbedder needs query as input and it's not getting it - "retriever.query" # from any component it's connected to, so it needs to receive it from the pipeline. - "prompt_builder.question" - "answer_builder.query" ``` ## Related Information - [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## Add Custom Code # Adding Custom Code Add custom Python code to enhance your pipelines. *** ## About This Task You can add custom Python code to your pipelines in two ways: - [With a `Code` component in Builder](./create-code-component.mdx) (recommended): Write your component code directly in Builder and test it right away. You can use it in a single pipeline or save it as a custom component to share with your workspace or organization. - [With a GitHub template](./add-custom-component.mdx): Write your component in your IDE using a GitHub template and upload it to . Best if you need external pip dependencies, full version control, or CI/CD testing. --- ## Add a Custom Component Learn how to create and upload custom components to . *** ## About This Task :::tip Recommended approach For most use cases, we recommend using the `Code` component to add custom code to your pipelines. You write the code directly in Builder, test it, and save it as a custom component to share with your workspace or organization — no GitHub setup required. For details, see [Add a Code Component](./create-code-component.mdx). ::: Use the GitHub template to create a custom component if you need: - External pip dependencies not already available in . - Full version control and CI/CD testing via GitHub Actions. For details on which approach fits your use case, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx). :::tip GPU Acceleration By default, pipelines and indexes run on CPU. If your component will work better on a GPU, you can turn on GPU acceleration in the pipeline or index settings. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). ::: ## Add a Custom Component To add a custom component to : 1. [Create a custom component](./create-a-custom-component.mdx). 2. [Upload the custom component](./upload-a-custom-component-to-deepset-cloud.mdx). --- ## Create a Custom Component Add components with custom code and use them in your pipelines. ## About This Task :::info Permissions You must be an organization Admin to upload custom components to . ::: ### What Are Custom Components A component is a Python code snippet that follows our template and performs a specific task on your data. When you create a custom component to , it becomes accessible to your entire organization. Any member can then use the component in their pipelines. Custom components are based on Haystack components. Haystack is 's open source AI framework, which also powers . To learn more, visit the [Haystack website](https://haystack.deepset.ai/). ### Custom Components Template Currently, you can't delete custom components. ### Custom Components in Pipeline Builder Custom components uploaded to are shown in the _Custom_ tab in Pipeline Builder. They're grouped automatically based on their path in the custom components package. For example, if your component is located at`/dc-custom-component-template/src/dc_custom_component/components/generators` in the package, it will show up under the _Generators_ group within the _Custom_ tab. ## Prerequisites - Read the following resources before completing this task: - [Haystack Components](https://docs.haystack.deepset.ai/docs/components) - [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) - [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) - You should have a basic understanding of working with GitHub repositories. - Generate a API key to upload the created component to your workspace. For instructions, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). ## Create a Component ### Prepare the Template 1. Fork the [dc-custom-component-template](https://github.com/deepset-ai/dc-custom-component-template) GitHub repository. This will let you version control your changes. 2. Navigate to the directory where you cloned the repository and open the `./dc-custom-component-template/src/dc_custom_component/example_components/` directory. The `preprocessors` and `rankers` folders are examples you can modify or remove as needed. 3. Create a new folder or rename one of the example folders to match your custom component's name and open it. There's a `.py` file inside. This is where you'll write your component code. You can rename this file as well. **Example**: To create a custom component called `WelcomeTextGenerator`: 1. Rename `./dc-custom-component-template/src/dc_custom_component/example_components/preprocessors` to `./dc-custom-component-template/src/dc_custom_component/components/generators`. 2. Open the `generators` folder and rename the example file `character_splitter.py` to `welcome_text_generator.py`. 3. Delete the `rankers` folder if it's not needed. If you're creating multiple components, use the folder structure to keep them organized. You can create all your components in one `.py` file or you can have a separate folder with a `.py` file in it for each custom component. That's up to you. :::info Component Folder as a Group Name The folder name containing your component code becomes the component group name in Pipeline Builder. For example, if you place your component in `./dc-custom-component-template/src/dc_custom_component/components/generators`, it will appear in the *Generators* group in the Pipeline Builder component library within the Custom tab. ::: ### Set Up a Virtual Environment Creating a virtual environment isolates your project's dependencies from other Python projects and your system Python installation. The template uses Hatch, a Python project manager, to set up virtual environments. For details, see the [Hatch website](https://hatch.pypa.io/latest/). 1. Install Hatch by running: `pip install hatch`. This installs all the necessary packages, including pytest. 2. Create a virtual environment by running: `hatch shell`. ### Implement the Component 1. Write the component code in the `.py` file. Use this code as a starting point: ```python from typing import Dict from haystack import component # import Haystack component object @component # add the class decorator class MyComponent: # create a class with a custom name, this will be your component's name # add docstrings to explain what your component does. You can use Markdown to format them. Docstrings are used in Pipeline Builder as component documentation. """ This component is an example of a custom component. To learn more, see [Custom Components](https://docs.cloud.deepset.ai/docs/custom-components) """ @component.output_types(welcome_text=str, note=str) # Add the `output_types` decorator and specify the output edge names and types of the component's outputs def run(self, name: str) -> Dict[str, str]: # Add the run() method. Make sure the types in the output dictionary are the same as the output types (in this example string and integer) # Add docstrings to explain the method and the parameters it takes. """ Generate the welcome text. :param name: The name the user provides. """ return { "welcome_text": ( "Hello {name}, welcome to Haystack!".format(name=name) ).upper(), "note": "welcome message is ready", } ``` 2. If your component has dependencies, add them in the `./dc-custom-component-template/pyproject.toml` file in the `dependencies` section: ```python dependencies = [ "haystack-ai>=2.0.0" ] ``` :::info Do not modify versions of dependencies already listed in this file. ::: 3. From the project root directory, run the `hatch run code-quality:all` command to format your code. 4. Update the component version in the `./dc-custom-component-template/src/dc_custom_component/__about__.py` file. You can specify version numbers in any way you like, but we suggest you adopt the major.minor.micro format, for example, 1.1.0. Have a look at [Hatch versioning](https://hatch.pypa.io/1.12/version/) for guidelines. The version number applies to all components. Even if you have multiple components, you only need to specify one version number. #### Components Connecting to Third-Party Providers If your component connects to a third-party provider that requires authentication, store the API key in an environment variable and then retrieve it in the component's `run()` method. You can also add a secret on the Secrets page and give it the same name as the environment variable. For details, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ### Test Your Component We recommend that you test your component before uploading. 1. Add unit and integration tests in the `./dc-custom-component-template/tests` folder to ensure everything works fine. 2. Run your tests using: `hatch run tests`. If the tests pass, your component is ready. ## What to Do Next [Upload your component to ](./upload-a-custom-component-to-deepset-cloud.mdx) to use it in your pipelines. --- ## Add a Code Component Use the `Code` component to execute your own Python code in a pipeline. It has built-in AI assistance to help you write the code. You can use it in a single pipeline or save it as a custom component to share with your workspace or organization. *** ## About This Task The `Code` component is the recommended way to add custom Haystack components in . You write the code directly in Builder, test it, and optionally save it as a custom component to reuse or share with others. Use the `Code` component if: - You want a fast and easy way to add custom code to a pipeline. - You prefer to add code directly in Builder rather than using a GitHub template and a CI/CD workflow. If you need external pip dependencies (beyond what's already available in deepset) or full GitHub-based versioning and CI/CD testing, consider creating a custom component with the GitHub template instead. For more information, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx). The component validates your code as you type it in the `code` field, so you can catch and fix any errors before deploying the pipeline. You can test your code by clicking **Run** on the component card and providing the component input. You should see the component's outputs in the Results panel. :::tip AI assistant You can use the AI assistant to generate the code for your `Code` component. To do this, click the **AI Assistant** button on the component card and write your request in the prompt. The AI generates the code for you. ::: :::tip GPU Acceleration By default, pipelines and indexes run on CPU. If your component works better on a GPU, you can turn on GPU acceleration in the pipeline or index settings. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). ::: ### Saving and Sharing Code Components You can save your `Code` component and share it with your workspace or organization. Saved components appear in the **Your Custom Components** section of the Component Library in Builder. Anyone with access can drag them into a pipeline from there. Components shared with the entire organization appear in the *Organization* section and components shared with the workspace appear in the *Workspace* section. When you add a saved `Code` component to a pipeline, the code is copied into that pipeline. Each pipeline gets its own independent copy, so updating the saved component later doesn't affect pipelines already using it. You can view and manage your saved components in organization or workspace settings, depending on the scope of the component. ### Permissions - To share a component with the entire organization, you need Organization Admin permissions. - To share a component with your workspace, you need workspace write permissions. ## Prerequisites - An understanding of components and their structure. For more information, see: - [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx) - [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) - You can also check the [Code component reference documentation](/docs/reference/pipeline-components/custom/Code.mdx). ## Add a `Code` Component 1. Go to **Pipelines** and click the pipeline you want to add the `Code` component to. The pipeline opens in Builder. 2. Click **Add**, find the `Code` component, and drag it onto the canvas. 3. Click the component card and type your code in the Python editor. Use the example as a starting point. Make sure your code has the `@component` decorator and the `run()` method. Define the inputs and outputs so that they match the inputs and outputs of the components it's connected to. :::tip AI assistant You can use the AI assistant to generate the code for your `Code` component. To do this, click the **AI Assistant** button on the component card and write your request in the prompt. The AI generates the code for you. :::
Example This is an example of a `Code` component that counts words in a text. The component takes a string as input and returns the number of words in the string and the original string. ```python @component class WordCounter: """ A component that counts words in a text. """ @component.output_types(count=int, original_text=str) def run(self, text: str): return { "count": len(text.split()), "original_text": text } ```
5. If your class defines `__init__` parameters, click the **Advanced** tab in the configuration panel to set their values. 6. Run the component to test it: 1. On the component card, click **Run**. 2. Enter the component inputs and click **Run Component**. You should see the component's outputs in the Results panel. 7. Connect the component to the other components it needs to work with. 8. Save your pipeline. ## Save a Code Component as a Custom Component To save a `Code` component as a custom component and reuse it in other pipelines: 1. On the component card, click **Save as Custom Component**. 2. Give the component a name and optionally a description. 3. Choose whether to share the component with the entire organization. If you leave this unchecked, the component is only available in your workspace. 4. Click **Save**. The component is now saved and appears in the **Your Custom Components** section of the Component Library. You and your team can drag it into any pipeline from there. ## Example Watch the gif to see how to add a `Code` component to a pipeline and save it as a custom component. ## What To Do Next To manage your saved components, go to **Settings** and navigate to the organization or workspace components section. There you can view all saved components and delete any that are no longer needed. ## Related Links - [Code Component Reference](/docs/reference/pipeline-components/custom/Code.mdx) - [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) - [Tutorial: Build a PII Masking Index with Custom Code](/docs/tutorials/learn-the-basics/tutorial-build-pii-masking-index.mdx) --- ## Troubleshoot Custom Components Fix the most common issues with custom components. *** ## Troubleshooting Upload Issues These are the issues that occur when component is ingested into but before it's installed. - If you're uploading through REST API or commands, you get an error response that will guide you through the steps to fix the issue. - If you're uploading by releasing the forked repository, go to the **Actions** tab of your repository and check the actions that failed. ## Troubleshooting Installation Issues These are the issues after the component is ingested into and attempts to install it. ### Symptoms Your component is not visible in the Pipeline Builder's component library. ### Actions 1. Refresh the Pipeline Builder page and wait a couple of minutes for the installation to complete. 2. If your component is still not visible, print the installation logs of the latest version of your custom components to check the issues that occurred: - On Linux and macOS, run: `hatch run dc:logs`. - On Windows, run: `hatch run dc:logs-windows`. ## Troubleshooting Operational Issues These are the issues that may occur when a component was correctly uploaded and is visible in Pipeline Builder, but fails to work correctly in a pipeline. | Symptoms | Action | | --- | --- | | Your component doesn't work in your pipeline. | Check the pipeline logs for issues and remedy actions: Go to **Pipelines** and click the name of the pipeline whose logs you want to see. Click the **Logs** tab on the Pipeline Details page to view all information message, warnings, and errors your pipeline produced. | | You see this error message: `Your organization's services are currently inactive due to user inactivity. Log in to to reactivate your services and try again. It may take a few minutes for the services to become fully operational.` | This means your organization's utility services were temporarily scaled down to save resources. Log in to and wait a while for the services to be activated. | --- ## Update a Custom Component To update custom components, upload their new version to . Compare different component versions to evaluate them. *** :::info Permissions You must be an organization Admin to upload custom components to . ::: ## Update a Component To update a custom component: 1. Pull the latest version of the [dc-custom-component-template](https://github.com/deepset-ai/dc-custom-component-template) repository. 2. Update the component code in the `./dc-custom-component-template/src/dc_custom_component/components//.py` file. 3. Update the component version in the `./dc-custom-component-template/src/dc_custom_component/__about__.py` file. :::info Checking the current version You can check the version of the component that's currently in in Pipeline Builder. Drag your custom component onto the canvas and its version is displayed on the component card. You can also use the [Get Custom Components](/docs/api/main/get-custom-component-api-v-2-custom-components-custom-component-id-get.api.mdx) endpoint - the version is listed in the `version` parameter of a successful response. ::: 4. If the component has any dependencies, add them in the `dependencies` section of the `./dc-custom-component-template/pyproject.toml` file. Do not modify versions of dependencies already listed in this file. 5. [Upload your component to .](./upload-a-custom-component-to-deepset-cloud.mdx). All new pipelines automatically use the latest version of your custom components. However, running pipelines continue to use the version that was current when they were deployed. To update the component version in running pipelines, undeploy and redeploy them. ## Compare Different Component Versions To evaluate which version of your component performs better in a pipeline, you can upload two versions of the component simultaneously, each with a unique name. 1. Pull the latest version of the [dc-custom-component-template](https://github.com/deepset-ai/dc-custom-component-template) repository. 2. Add two versions of the component to the `./dc-custom-component-template/src/dc_custom_component/components//.py` file, treating them as separate components and giving each version a distinct name. 3. Update the component version in the `./dc-custom-component-template/src/dc_custom_component/__about__.py` file. 4. [Upload your components to .](./upload-a-custom-component-to-deepset-cloud.mdx). Now, you can create two pipelines—one using the first version and another using the second—to compare their performance. --- ## Upload a Custom Component to deepset # Upload a Custom Component to After you implement and test your component, upload it to to use it in your pipelines. *** ## About This Task :::info Permissions You must be an organization Admin to upload custom components to . ::: To use your component in , you must upload it first. There are three ways to upload your component: - By creating a release of your forked repository (recommended if multiple users collaborate on the repository, lets you version control your code) - Through REST API - Using commands (currently supported for Linux and macOS) When you upload a component, we verify the structure and version of the uploaded ZIP file. ## Prerequisites - Make sure you test your component before uploading. - Make sure your component code follows appropriate linting and formatting conventions. You can use the `hatch run code-quality:all` command to check the linting. ## Upload Your Component ### Upload by Creating a Release We use GitHub actions to build and import custom components to . Before importing the component, the action runs the tests and checks the code quality. Only if those pass, the component is imported. The action is triggered when you create a tag for a release in your GitHub repository. For details on tags and releases, see [GitHub documentation](https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases). 1. Before you start importing, make sure you pushed all your changes to the forked repository. 2. Add the `DEEPSET_CLOUD_API_KEY` secret to your repository: 1. Go to *Settings > Secrets and variables > Actions*. 2. Click **New repository secret**. 3. Type `DEEPSET_CLOUD_API_KEY` as the secret name, paste the API key in the _Secret_ field, and click **Add secret**. 3. Make sure your repository has workflows enabled: Go to _Actions_ and click **Enable workflows**. (If they're enabled, you won't see this option.) 4. Create a new release: 1. In the left-hand navigation, click **Releases** and choose **Draft a new release**. 2. Create a tag for your release. **Note:** The version you specified in the `__about__` file will be overwritten by the tag value. Make sure the tag matches the version number. 3. Publish your release. This starts the tests and code quality check. You can monitor the action progress in the Actions tab of your repository. Once all the tests and checks finish successfully, your component is imported to . ### Upload with REST API 1. Zip the repository from the template folder. The zipped repository should contain the same files in the same hierarchy as the `dc-custom-component-template` repository. This command creates a ZIP file called `custom_component.zip` in the parent directory: ```shell Linux and macOS zip -r ../custom_component.zip ./* ``` ```shell Windows Compress-Archive -Path .\* -DestinationPath ..\custom_component.zip -Force ``` 2. Upload the ZIP file to using the [Import Custom Components](/docs/api/main/import-custom-components-api-v-2-custom-components-post.api.mdx) endpoint. Here's a sample code you can use as a starting point for your request: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v2/custom_components \ --header 'accept: application/json' \ --header 'Authorization: Bearer api_XXX' \ --form 'file=@"/path/to/custom/component/custom_component.zip";type=application/zip' ``` ```python url = "https://api.cloud.deepset.ai/api/v2/custom_components" files = { "file": ("custom_component.zip", open("path/to/custom_component.zip", "rb"), "application/x-zip-compressed") } headers = { "accept": "application/json", "authorization": "Bearer deepset_cloud_API_key" } response = requests.post(url, files=files, headers=headers) print(response.text) ``` ### Upload with Commands This method is currently available for Linux and macOS systems. 1. Set your API key: ```shell export API_KEY= ``` 2. From within this project (custom component template),run the following command to upload your custom component: ```shell hatch run dc:build-and-push ``` This command creates a ZIP file called `custom_component.zip` in the `dist` directory and uploads it to . ## Verify the Upload Check the component status using the [Get Custom Component](/docs/api/main/get-custom-component-api-v-2-custom-components-custom-component-id-get.api.mdx) endpoint. If the status is `finished`, your component is ready for use in your pipelines. Here is a sample code you can use: ```python url = "https://api.cloud.deepset.ai/api/v2/custom_components" headers = { "accept": "application/json", "authorization": "Bearer deepset_cloud_API_key" } response = requests.get(url, headers=headers) print(response.text) ``` ```curl curl --request GET \ --url https://api.cloud.deepset.ai/api/v2/custom_components \ --header 'accept: application/json' \ --header 'authorization: Bearer deepset_cloud_API_key' ``` :::info It takes a while for the custom component to be available in Pipeline Builder. Refresh the page and wait a couple of minutes. ::: ## What to Do Next Once the component is successfully uploaded to , you can use it in your pipelines. The component will be visible in Pipeline Builder's components library within the Custom tab. (To access Pipeline Builder, find your pipeline on the Pipelines page and choose _Edit_ from the More Actions menu next to it.) In the component library, your component is in a group whose name is the same as the name of the template folder where you saved your component. For example, if you component code is in `./dc-custom-component-template/src/dc_custom_component/rankers/my_ranker.py`, you'll find it in the Rankers group. --- ## Building with Large Language Models (LLMs) LLMs show remarkable capabilities in understanding and generating human-like text. Learn how you can use them in your pipelines. *** ## LLMs in Your Pipelines You can easily integrate LLMs in your pipelines using the versatile `LLM` component. `LLM` works well for retrieval augmented generation (RAG) question answering and other tasks such as text classification, summarization, and more. It performs the specific task you define within the prompt you configure. To build autonomous systems that make decisions, use the [Agent](/docs/concepts/ai-agents/ai-agent.mdx) component. It uses an LLM as its decision-making brain and can call tools you provide. For a deeper explanation of decision-making systems, check [Agentic Pipelines](/docs/concepts/ai-agents/agentic-pipelines.mdx). # Agents offers an Agent component powered by an LLM of your choice. It can call and run tools, reason, and make autonomous decisions. Try it out in your pipelines or use the pipeline templates we prepared. You can find them on the Pipeline Templates page under _Agents_. To learn more, see [Agents](/docs/concepts/ai-agents/ai-agent.mdx). ## Ready-Made Templates for LLM Apps Pipeline Templates in offer a variety of ready-made templates you can use with default settings. Templates with RAG in the title use an LLM and have streaming enabled by default. In the *Conversational* category, you'll find RAG Chat templates designed specifically for chat scenarios, such as customer assistants. These chat pipelines include chat history in their responses, ensuring the LLM considers this information to create a human-like conversation experience. All chat pipelines have streaming enabled by default. There's also a group of Agent templates with tools such as web search and RAG already configured. Check the _Agent_ group. ## Streaming ## Tool Calling Also known as function calling, tool calling is the ability of the model to use external tools to resolve queries. When given the tools, the LLM decides which one to use, and then calls it. In , you can add an Agent component and configure its tools. For details, see [Configure the Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). ## Learn more Here's a collection of information you may want to explore for more information related to LLMs and generative AI in . ### About LLMs - [Language Models](/docs/learn/large-language-models-overview.mdx) - [Recommended Models](/docs/learn/models-1.mdx) - [RAG Question Answering](/docs/learn/generative-question-answering.mdx) ### Agents - [Building AI Agents](/docs/how-to-guides/building-agents/building-ai-agents.mdx) - [Tutorial: Building an IT Helpdesk Agent](/docs/tutorials/build-agents/tutorial-building-helpdesk-agent.mdx) ### Generative AI in Practice - [Tutorial: Building a Robust RAG System](/docs/tutorials/learn-the-basics/tutorial-building-a-robust-rag-system.mdx) - [Enable References for Generated Answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx) - [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx) ### Prompt Engineering - [Prompt Engineering Guidelines](/docs/learn/prompt-engineering-guidelines.mdx) - [Writing Prompts in ](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx) - [Engineering Prompts in Prompt Explorer](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx) --- ## Enable References for Generated Answers Enhance your AI-generated answers with source references to make your app more trustworthy and verifiable. *** ## About This Task When using an LLM to generate answers, making it cite its resources can significantly enhance the credibility and traceability of the information provided. In the prompt, instruct the LLM to generate references. :::info Pipeline Templates The reference functionality is already included in RAG pipeline templates in . The default prompt instructs the LLM to generate references to the documents it used to generate the answer. ::: ## Adding References with an LLM To add references using an LLM, add specific instructions in your prompt. Here is a prompt we've tested and recommend for you to use: ```jinja2 You are a technical expert. You answer the questions truthfully on the basis of the documents provided. For each document, check whether it is related to the question. To answer the question, only use documents that are related to the question. Ignore documents that do not relate to the question. If the answer is contained in several documents, summarize them. Always use references in the form [NUMBER OF DOCUMENT] if you use information from a document, e.g. [3] for document [3]. Never name the documents, only enter a number in square brackets as a reference. The reference may only refer to the number in square brackets after the passage. Otherwise, do not use brackets in your answer and give ONLY the number of the document without mentioning the word document. Give a precise, accurate and structured answer without repeating the question. Answer only on the basis of the documents provided. Do not make up facts. If the documents cannot answer the question or you are not sure, say so. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: ``` --- ## Enable Streaming Streaming refers to a large language model generating text as it's produced rather than waiting for the entire response to be ready before showing it. It's similar to watching someone type real-time. Enable streaming for the LLMs in your pipelines. *** ## About This Task Streaming is a technique often used in chat interfaces. It makes the responses seem faster as users can immediately see the output and can start reading while the rest of the text generates. It also makes it possible to interrupt the LLM if needed. This is particularly useful for longer responses where waiting for the generation to complete may take a couple of seconds. In , streaming is enabled by default for all LLMs. ### Streaming in API endpoints When using through the API, use the `stream` endpoints to get streaming responses. For example, use the [Chat Stream](/docs/api/main/chat-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-stream-post.api.mdx) endpoint to get a streaming response from a chat pipeline or the [Search Stream](/docs/api/main/search-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-stream-post.api.mdx) endpoint to get a streaming response from a search pipeline. ## Configure Streaming Components Use the top-level `streaming_components` field in your pipeline YAML to control which components stream their output. This is the recommended way to configure streaming. It works consistently across both the Playground and the API endpoints. ### Enable Streaming for Specific Components To specify which components should stream, list their names in the `streaming_components` field: ```yaml max_runs_per_component: 100 streaming_components: - llm_1 - llm_2 - agent components: llm_1: type: haystack.components.generators.chat.openai.OpenAIChatGenerator # ... component configuration llm_2: type: haystack.components.generators.chat.openai.OpenAIChatGenerator # ... component configuration agent: type: haystack.components.agents.agent.Agent # ... component configuration ``` ### Enable Streaming for All Components To enable streaming for all compatible components in your pipeline, use the wildcard value: ```yaml max_runs_per_component: 100 streaming_components: all components: # ... your pipeline components ``` ### Default Behavior If you don't include the `streaming_components` field, only the last streaming-capable component in your pipeline streams its output. ## Legacy: Streaming with `streaming_callback` :::info Legacy Approach This approach is supported for backward compatibility with existing pipelines. For new pipelines, use the [`streaming_components` field](#enable-streaming-for-specific-components) instead. ::: Older pipelines may have streaming enabled by setting the `streaming_callback` init parameter on individual components instead of using the `streaming_components` YAML field. This approach only works predictably in the Playground. The API uses the same behavior by default: `include_tool_calls` defaults to `"rendered"`, which embeds tool calls as inline markdown in `delta` events rather than emitting separate `tool_call_delta` events. See [Stream request parameters](#stream-request-parameters) for details. For legacy pipelines that use `streaming_callback`, Hayhooks hybrid mode is enabled by default (`allow_sync_streaming_callbacks: true`). You can disable it by passing `allow_sync_streaming_callbacks: false` in your stream request. For legacy pipelines, set streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback on each component you want to stream. All configured components receive streaming output through the API. This differs from the `streaming_components` field: when you omit that field, only the last streaming-capable component streams by default. ### Generators and ChatGenerators ```yaml CohereGenerator: type: haystack_integrations.components.generators.cohere.generator.CohereGenerator init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: command-r streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback ``` ### Agents For agents, `streaming_callback` is set at the agent level, not on the inner `chat_generator`: ```yaml agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o streaming_callback: # leave empty on the inner generator system_prompt: You are a deep research assistant. streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback tools: # ... ``` ## Streaming with API You can use streaming with the `stream` API endpoints: [Chat Stream](/docs/api/main/chat-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-stream-post.api.mdx) and [Search Stream](/docs/api/main/search-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-stream-post.api.mdx). This is an example request to the `Search Stream` endpoint. ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/WORKSPACE_NAME/pipelines/PIPELINE_NAME/search-stream \ --header 'accept: application/json' \ --header 'authorization: Bearer DEEPSET_API_KEY' \ --header 'content-type: application/json' \ --data ' { "debug": false, "include_result": true, "view_prompts": false, "query": "who started all-girl bands?" } ' ``` ```python url = "https://api.cloud.deepset.ai/api/v1/workspaces/WORKSPACE_NAME/pipelines/PIPELINE_NAME/search-stream" payload = { "debug": False, "include_result": True, "view_prompts": False, "query": "who started all-girl bands?" } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer DEEPSET_API_KEY" } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` Replace: - `WORKSPACE_NAME`: With the name of the workspace containing your pipeline. - `PIPELINE_NAME`: With the name of the pipeline to use for search. - `DEEPSET_API_KEY`: With your API key. ### Default Streaming Behavior in the API By default, the streaming endpoints only stream output from the **last streaming-capable component** in your pipeline. This matches the default pipeline behavior described in the [Default Behavior](#default-behavior) section above. To stream output from more than one component or from a specific component, configure the `streaming_components` field in your pipeline YAML before using the API. See [Enable Streaming for Specific Components](#enable-streaming-for-specific-components) for details. ### Stream Request Parameters These request body fields control which SSE event types you receive from `search-stream` and `chat-stream`: | Parameter | Default | Effect | |---|---|---| | `include_result` | `false` | When `true`, emits a `result` event with the full pipeline output at the end of the stream | | `include_tool_calls` | `rendered` | Controls how agent tool calls appear in the stream (see below) | | `include_tool_call_results` | `false` | When `true`, emits `tool_call_result` events after each tool completes | | `include_reasoning` | `false` | When `true`, emits `reasoning` events during model reasoning steps | | `allow_sync_streaming_callbacks` | `true` | When `true`, enables Hayhooks hybrid mode for pipelines that use legacy sync-only `streaming_callback` components | | `chat_history_granularity` | `QUERY_ANSWER` | Controls how much chat history is replayed to agent pipelines on each turn (see below) | #### `include_tool_calls` The default is `rendered`. This setting only affects agent pipelines that make tool calls: | Value | Behavior | |---|---| | `rendered` (default) | Tool calls are rendered as inline markdown inside `delta` events. No `tool_call_delta` events are emitted. | | `true` | Tool calls emit structured `tool_call_delta` events as they progress | | `false` | Tool calls are omitted from the stream entirely | The `rendered` default matches Playground behavior and is the simplest option for chat-style UIs. Set `include_tool_calls` to `true` when you need programmatic access to tool names, arguments, and call IDs with `tool_call_delta` events. #### `chat_history_granularity` This setting controls how much of the conversation history is sent back to the pipeline on each turn. It is most relevant for agent pipelines, where intermediate tool calls, tool results, and reasoning steps are part of the conversation. | Value | Behavior | |---|---| | `QUERY_ANSWER` (default) | Only the user query and the final assistant answer from each previous turn are included in the history. | | `ALL_MESSAGES` | The full message trace from each previous turn is included — tool calls, tool results, reasoning steps, and the final answer. | Use `ALL_MESSAGES` when your agent pipeline relies on tool call context across multiple turns. For example, if a user follows up on a previous tool-assisted response, `ALL_MESSAGES` makes sure the agent receives the complete prior context and does not lose track of earlier tool use. :::info Token Usage Using `ALL_MESSAGES` increases the amount of context sent to the model on each turn. This can increase token usage and costs compared to the default `QUERY_ANSWER` mode. ::: You can also set this per pipeline in the pipeline YAML under the `history` key: ```yaml history: granularity: all_messages ``` When both the API request and the pipeline YAML specify a value, the API request value takes precedence. If neither is set, the default is `QUERY_ANSWER`. ### Streaming Event Types The streaming endpoints use [Server-Sent Events (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) and return a sequence of events. Each event has a `type` field that identifies what it contains. Most events also include a `query_id`. The `ping` event is the only exception. The event types are mutually exclusive, each event carries exactly one of the following: | Event type | When it's sent | What it contains | |---|---|---| | `delta` | During generation | `delta` object with `text` and `meta`; optional `start` (first chunk from a component), `finish_reason` (when generation ends), and `index` (component index when multiple components stream) | | `result` | End of stream (when `include_result=true`) | The full pipeline result | | `error` | When the pipeline fails | An error message. Terminal — no further events follow it. | | `tool_call_delta` | During agent tool use (only when `include_tool_calls=true`) | Structured information about a tool call in progress. Not emitted when the default `"rendered"` mode is used | | `tool_call_result` | After a tool call completes (when `include_tool_call_results=true`) | The result returned by a tool | | `reasoning` | During agent reasoning (when `include_reasoning=true`) | A reasoning step from the model | | `ping` | Periodically | Keep-alive signal. Contains only `type` — no `query_id` or other fields | #### The `delta` Event `delta` events carry incremental text as the pipeline generates a response. The `delta` object holds the new text and metadata (including which component produced the chunk). Three optional top-level fields help you format output across multiple streaming components: | Field | Type | When present | Meaning | |---|---|---|---| | `start` | boolean | First chunk from a component | `true` marks the beginning of output from that component | | `finish_reason` | string | Last chunk from a component | Why generation stopped: `stop`, `length`, `tool_calls`, `content_filter`, or `tool_call_results` | | `index` | integer | Multiple streaming components | Identifies which content part is being updated | ```json { "type": "delta", "query_id": "290a1f96-57d6-4843-8ed7-2a224142398b", "delta": { "text": "Hello", "meta": { "deepset_cloud": { "component": "llm_1" } } }, "start": true, "finish_reason": "stop", "index": 0 } ``` `start`, `finish_reason`, and `index` are omitted when they do not apply to a given chunk. #### The `error` event Every failed stream ends with an `error` event. The event includes a human-readable `error` message. The `error` frame is terminal — no further events follow it. ```json { "type": "error", "query_id": "290a1f96-57d6-4843-8ed7-2a224142398b", "error": "Invalid pipeline configuration." } ``` #### The `ping` event The server sends `ping` events periodically to keep the connection alive during long-running streams. Unlike every other event type, `ping` carries no `query_id` — only the `type` field: ```json { "type": "ping" } ``` You can safely ignore `ping` events in your client logic. Here is an example showing how to handle all event types. The example sets `include_tool_calls` to `true` so that structured `tool_call_delta` events are emitted — omit this field to use the default `"rendered"` mode, where tool calls appear as markdown inside `delta` events instead: ```python from httpx_sse import EventSource TOKEN = "DEEPSET_API_KEY" PIPELINE_URL = "https://api.cloud.deepset.ai/api/v1/workspaces/WORKSPACE_NAME/pipelines/PIPELINE_NAME" async def main(): query = { "query": "How does streaming work with deepset?", "include_result": True, # Default is "rendered" (tool calls as markdown in delta events). # Set to true to receive structured tool_call_delta events instead: "include_tool_calls": True, "include_tool_call_results": True, } headers = { "Authorization": f"Bearer {TOKEN}" } async with httpx.AsyncClient(base_url=PIPELINE_URL, headers=headers, timeout=httpx.Timeout(300.0)) as client: async with client.stream("POST", "/search-stream", json=query) as response: if response.status_code != 200: await response.aread() print(f"An error occurred with status code: {response.status_code}") print(response.json()["errors"][0]) return event_source = EventSource(response) async for event in event_source.aiter_sse(): event_data = json.loads(event.data) chunk_type = event_data["type"] match chunk_type: case "delta": delta = event_data["delta"] if event_data.get("start"): component = delta.get("meta", {}).get("deepset_cloud", {}).get("component", "unknown") print(f"\n[Component: {component}] ", end="", flush=True) print(delta.get("text", ""), end="", flush=True) case "result": print("\n\n[Full Result]") print(json.dumps(event_data, indent=2)) case "tool_call_delta": print(f"\n[Tool Call] {json.dumps(event_data, indent=2)}") case "tool_call_result": print(f"\n[Tool Result] {json.dumps(event_data, indent=2)}") case "reasoning": print(f"\n[Reasoning] {event_data.get('reasoning', {}).get('text', '')}", flush=True) case "error": print(f"\n[Error] {event_data.get('error', 'Unknown error')}") case "ping": pass # ignore keep-alive pings case _: print(f"\n[Unknown event type: {chunk_type}]") asyncio.run(main()) ``` ## Next Steps - [Chat Stream API reference](/docs/api/main/chat-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-stream-post.api.mdx) - [Search Stream API reference](/docs/api/main/search-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-stream-post.api.mdx) --- ## Set Up Tool Calling For Your Model Configure tools your chat model can use to answer the query. *** :::info Tool Calling with Agent We recommend using tools with the Agent component. For details, see [Agent](/docs/concepts/ai-agents/ai-agent.mdx). You can also use tools with an [Agent](/docs/concepts/ai-agents/ai-agent.mdx) component. For an overview of different ways to set up tool calling and their advantages, see [Agentic Pipelines](/docs/concepts/ai-agents/agentic-pipelines.mdx) and [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx). ::: ## About This Task Tool calling, also known as function calling, lets the LLM in your app call a pipeline component. This is useful when the model needs information or capabilities beyond what it knows, such as retrieving real-time data. ## Set Up Tool Calling We recommend using tools with the Agent component. For details, see [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx) and [Configuring Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). --- ## Using Prompt Explorer` # Using Prompt Explorer Prompt Explorer is a powerful tool in that lets you view, analyze, and manage all the prompts used in your pipelines. You can use it to test your prompts and compare their performance. It comes with a library of ready-to-use prompts where you can also save your own prompts. Prompt Explorer automatically detects and displays all prompts from your deployed pipelines. ## About This Task Prompt Explorer is a sandbox environment where you can: - Test different versions of your prompts before bringing them to production. - Modify your prompts. - Compare the same prompt across up to three pipelines. - Update your pipelines with refined prompts. - Save custom prompts to the library and reuse them later. - Modify pipeline parameters for a single query without changing pipeline configuration. For details, see [Modify Pipeline Parameters at Query Time]. ## Accessing Prompt Explorer Prompt Explorer is only available for deployed pipelines that use at least one LLM. In the navigation, click **Prompt Explorer**: It opens Prompt Explorer, with Prompt Editor and a template repository. ## Testing and Modifying Prompts Use the Prompt Editor within the Prompt Explorer to modify your prompts and observe how they affect the results. You can experiment with different versions of prompts for the same query and review the history of your results. Prompts must conform to the [Jinja2 ](https://palletsprojects.com/p/jinja/)template language. Prompt Explorer supports Markdown formatting of prompts. Using the expanding list at the top, you can choose a pipeline. The pipeline must have at least one component with prompt, such as `Agent` or `LLM`. Once you choose a pipeline, its prompt immediately shows in the Prompt Editor at the bottom. If there are multiple components with prompts in the pipeline, you can choose the one you want to work with. Use the Editor to modify your prompt and run queries. To check the history of your queries, click the clock icon next to the query (it's only available if you select a single pipeline). You can preview the rendered prompt by clicking the More Actions icon next to the generated answer. **Legend**: 1. Pipeline selection. You can only select pipelines that have at least one component with a prompt, like `Agent` or `LLM`. 2. Chat history. 3. Use this menu to: - Add another pipeline to compare. - Access more actions, like exporting the conversation or copying it. - Accessing filters and parameters. 4. Response actions. You can give feedback, copy, download, and bookmark the response. 5. View the prompt used to generate this response. 6. Prompt selection. Choose the component and the prompt to test. 7. Prompt menu. Use it to: - Update the prompt in yoru pipeline. This creates a new pipeline version with the updated prompt without deploying it or modifying the current draft. - View prompt templates saved in the prompt library. - Enable Jinja2 syntax. - Copy the prompt. 8. Query. ## Using Prompt Templates You can save your prompt as a template and then reuse it across your pipelines. Choose a prompt from a library and test it in Prompt Explorer. The prompt you choose shows in Prompt Editor where you can further modify it if needed. In Prompt Editor, click **Templates**. The _Custom_ tab lists the prompts you saved. ## Saving Custom Prompts Save your prompts in the library so you can use them in the future. 1. In Prompt Explorer, next to the prompt, click **Prompt Templates**. 2. On the _Custom_ tab, click **Create Custom Prompt**. 3. Name the prompt, type the prompt text, and save your prompt. Add variables to the prompt using [Jinja2 syntax](https://palletsprojects.com/p/jinja/), for example: ```Jinja2 Given these documents, answer the question.\nDocuments: {% for doc in documents %} {{ doc.content }} {% endfor %} \nQuestion: {{query}} \nAnswer: ``` ## Updating the Prompt in the Pipeline Once you've tested a prompt and want to save it, click **Update**. This creates a new pipeline version containing your updated prompt. :::info Clicking **Update** does not deploy the new version or modify your current draft. To make the updated prompt live, deploy the new version manually. ::: ## Comparing Pipelines You can compare up to three pipelines. This is useful if you have pipelines using different models to understand how they perform. You pass the same query to all the pipelines you're comparing, but you can modify the prompts for each pipeline. To add a pipeline to comparison, click **Add Pipeline** at the top of the Playground. You can then add or remove pipelines using the plus (+) and minus (-) icons: Each pipeline receives the same query, but you can change the prompt for each pipeline. ## Test Configurations Without Changing Your Pipeline You can experiment with different component settings for a single query—without changing your saved pipeline configuration. Use the Configurations option in the top right corner of Prompt Explorer available when you choose a pipeline. ## Troubleshooting If you don't see your prompts: - Ensure your pipeline is deployed. - Ensure your pipeline has at least one component with prompt, such as `Agent` or `LLM`. - Ensure your prompt is valid Jinja2 syntax. ## Related Information - [Writing Prompts in Haystack Enterprise Platform](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx) - [Building with Large Language Models](/docs/how-to-guides/designing-your-pipeline/work-with-llms/build-with-llms.mdx) - [Deploying Pipelines](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) --- ## Writing Prompts in Haystack Enterprise Platform # Writing Prompts in In , prompts use Jinja2 syntax, which makes it possible to add variables or expressions that are replaced with real values when the template is rendered. This way, you can include dynamic content, like documents and queries, in the prompt. ## Jinja Templates Jinja2 is a templating engine that enables dynamic templates in static content by embedding placeholders, such as variables. These placeholders are filled with actual values when the template is rendered. Jinja2 also supports advanced features like loops and conditionals. The variables you use in a prompt template correspond to outputs from preceding components in your pipeline. When the pipeline runs, each variable is replaced with the data that flows from the component you connected to that input. For example, if you connect a `Retriever` to an `LLM` component, you can add a `documents` variable to the `LLM`'s prompt. At runtime, that variable is replaced with the actual documents the Retriever returned, because the Retriever outputs documents and passes them to the `LLM` when they are connected. The same applies to other variables: use the name of the output you want (such as `question` or `query` for the user input) and connect the corresponding component so the value is supplied at runtime. :::tip Jinja in the `LLM` and `Agent` components `LLM` and `Agent` components have a rich editor for Jinja2 templates. This applies to both system and user prompts. When you add or edit a prompt for the `LLM` component, you write regular text. To insert a variable, type **`@`** and a list of available variables appears so you can pick one. To insert a function, type **`/`** and you see all functions you can add to the template. If you want to type a literal `@` or `/` character instead of opening the list, press **Escape** after the list appears and the character is inserted into your prompt. To see the raw Jinja2 syntax, enable the **Jinja** toggle. It's disabled by default. ::: To learn more about Jinja2 syntax, see [Jinja2 documentation](https://jinja.palletsprojects.com/en/3.0.x/templates/). ## Prompt Types There are two main types of prompts: system prompts and user prompts. Both types support dynamic content through Jinja2 syntax. ### System Prompts System prompts define the LLM's behavior, personality, and operational guidelines. They are used to set the overall behavior, persona, and context for the model. They're applied at the start of every request. These are typically used by `Agent` and `LLM` components. For models that use the `ChatMessage` format, you type system prompts as `ChatMessage` objects with the `system` role. ```yaml - content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. role: system ``` ### User Prompts User prompts contain the actual queries or instructions from users. They are commonly used in chat-based pipelines. For models that use the ChatMessage format, user prompts are passsed as `ChatMessage` objects with the `user` role. ```yaml - content: - text: | What is the capital of France? role: user ``` ## Passing a Prompt to the Model ### Using the LLM or Agent Components When using the `LLM`, you can pass the system and user prompts directly in the component configuration. You can also use Jinja2 syntax to insert variables into the prompt. ```yaml components: llm: type: haystack.components.generators.chat.llm.LLM init_parameters: system_prompt: "You are a helpful assistant that answers user's questions." user_prompt: "Answer the question: {{ query }}" ``` You can only insert variables that the component receives as input from preceding components in the pipeline. In the example above, the `LLM` can receive the `query` variable if the `Input` component's `query` output is connected to the `LLM`'s `messages` input. Similarly, it can receive the `documents` variable if the `Retriever` component's `documents` output is connected to the `LLM`'s `documents` input. ### Using the PromptBuilder and Generator Components :::warning Legacy approach We recommend using the `LLM` component instead. You can use it instead of `PromptBuilder` and `Generator` components. It works with any LLM provider and replaces both components. For details, see [LLM](/docs/reference/pipeline-components/ai/LLM.mdx). :::
Click to read the instructions With this approach, you need two components connected together: `PromptBuilder` and a `Generator`. You pass the prompt in `PromptBuilder`'s `template` parameter. At search time, `PromptBuilder` renders the template, fills in the variables with real values, and sends the rendered prompt to the `Generator`. The `Generator` is essentially the LLM. There's a `Generator` for each model provider, for example, `OpenAIGenerator`, `CohereGenerator`, and so on. When the pipeline runs, the `Generator` receives the prompt with all variables filled in and generates a response based on the instructions. This is an example of using `PromptBuilder` in Pipeline Builder with a basic prompt template. It contains two variables: `question` and `documents`, which will be populated with the user query and retrieved documents and then sent to the Generator: #### YAML Example: PromptBuilder Template ```yaml # ... prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: ``` `PromptBuilder` requires the user query and the documents as inputs to fill in the prompt. In this example, it receives user query from the `Input` component and documents from the `Ranker` component (or any other component providing documents): #### YAML Example: Pipeline Connections ```yaml connections: # ... - sender: ranker.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: llm.prompt max_loops_allowed: 100 metadata: {} inputs: query: - prompt_builder.question ``` For more on variables, see the [Adding Variables to Prompts](#adding-variables-to-prompts) section below.
### ChatPromptBuilder and ChatGenerator :::warning Legacy approach This is a legacy approach and will be deprecated in future releases. We recommend using the `LLM` component instead. It works with any LLM provider and replaces both `ChatPromptBuilder` and `ChatGenerator` components. For details, see [LLM](/docs/reference/pipeline-components/ai/LLM.mdx). :::
Click to read the instructions ChatGenerators receive the prompt from `ChatPromptBuilder`. You can configure the prompt using `ChatPromptBuilder`'s `template` parameter. `ChatGenerators` require a list of `ChatMessage` objects as input, which means the format of the prompt must comply with the `ChatMessage` format: If you set `content_type` to `text`, it accepts Jinja2 syntax and you can pass variables in your prompt. The variables then become the required input for the component. #### Example ChatPromptBuilder Prompt This is an example of a `ChatPromptBuilder` template. The first `ChatMessage` contains text and is for the system role. These are the instructions for the model that set the general tone and purpose of the conversation. The second `ChatMessage` is the user query. Note that we're also passing the retrieved documents to the model in this message. There are two variables in this prompt: `query` and `documents`, they become the required input for `ChatPromptBuilder`. This means it must be connected to the `Input` component and to a component that produces the documents. ```yaml - content: - text: | You are a helpful assistant answering the user's questions based on the provided documents. If the answer is not in the documents, rely on the web_search tool to find information. In this case you must pass the user's question as query to the web_search tool. Do not use your own knowledge. role: system - content: - text: | # this makes it possible to use Jinja2 syntax Provided documents: {% for document in documents %} Document [{{ loop.index }}] : {{ document.content }} {% endfor %} Question: {{ query }} role: user ``` As you can see, `ChatMessages` can also contain variables, just like regular prompts, if the `content_type` is `text`. For details on `ChatMessage`, see [Haystack documentation](https://docs.haystack.deepset.ai/docs/chatmessage). #### ChatPromptBuilder with Jinja2 Template Syntax You can also pass ChatMessages as Jinja2 strings using the `{% message %}` tag. This makes it possible to test prompts in `ChatPromptBuilder` through Prompt Explorer. For example, this ChatPromptBuilder contains instructions for follow up question classification and rewriting queries at the start of the pipeline. There are two chat messages, one with role "system" and another one with role "assistant". It also includes chat history. ```text {% message role="system" %} You are a helpful assistant. {% endmessage %} {% message role="user" %} Hello! My name is {{user_name}}. {% endmessage %} ```
## Adding Variables to Prompts You can use Jinja2 syntax to insert variables into your prompts. Each variable is replaced with real values when the pipeline runs. The values come from the components that are connected upstream in your pipeline: whatever a component outputs (for example, `documents` from a Retriever, or `query` from the Input component) can be used as a variable in the prompt, as long as the components are connected so that the prompt receives the values at runtime. The prompt template is rendered with these values and then the final prompt is sent to the LLM. For example, in this prompt, the variable `{{ question }}` is a placeholder for the user query: ```jinja2 You are a technical expert. You answer questions truthfully based on your knowledge. Ignore typing errors in the question. Question: {{ question }} Answer: ``` In this example, prompt needs the query. In Builder, you simply connect the `Input` component's `query` output to the prompt's `question` input: The variable name in the template must match the input name. Use the at (`@`) symbol to see all available variables and add them to your prompt. At search time, `{{ question }}` is replaced with the actual user query: ```jinja2 You are a technical expert. You answer questions truthfully based on your knowledge. Ignore typing errors in the question. Question: what was wynton kelly famous for? Answer: ``` ### Required and Optional Variables By default, all variables in the template are considered optional. If they're not provided, they're replaced with empty strings. ### Required Variables You can indicate which variables are required and must be provided when the component is executed by listing them in the Required Variables field on the component card. If you do this, then the pipeline returns an error if any of the required variables is not provided at run time. Choose the variables from a list or choose **All** to make all variables in the prompt required. ### Additional Variables Use the `variables` parameter to define the full set of template variables that the component expects or can accept. If you don't set the variables explicitly, the component infers them by parsing the Jinja2 syntax from the `template` parameter. To define variables beyond those in the default template, for example for dynamic prompt switching or prompt engineering, you can set them manually in the `variables` parameter. These variables then become the inputs for the component. ### Variables with Attributes When adding a variable, you can reference its attributes to include them in the prompt. For example, you might want to use attributes from the `document` object, such as: - `id` - `content` - `meta` (metadata key) - `score` To reference these attributes, use the syntax: `.`. For attributes like meta, you can specify the key you want. For instance, to include the `date_created` metadata key, use: `document.meta.date_created`. This Jinja2 expression adds the document's score, content, and date_created metadata key to the prompt: ```jinja2 You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. Here are the documents: {% for document in documents %} Document[{{ loop.index }}]: Date created: {{ document.meta.date_created }} {{ document.content }} {% endfor %} Question: {{ question }} Answer: ```
Rendered prompt ``` You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. Here are the documents: Document[1]: Date created: 19-Aug-2004 deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- More Than One Way To Do It deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Okay, the Zen doesn't say that there should be Only One Way To Do It. But it does have a prohibition against allowing "more than one way to do it". ''''''''Response '''''''' There is no such prohibition. The "Zen of Python" merely expresses a *preference* for "only one *obvious* way":: There should be one-- and preferably only one --obvious way to do it. The emphasis here is that there should be an obvious way to do "it". In the case of dict update operations, there are at least two different operations that we might wish to do: - *Update a dict in place*: The Obvious Way is to use the ``update()`` method. If this proposal is accepted, the ``|=`` augmented assignment operator will also work, but that is a side-effect of how augmented assignments are defined. Which you choose is a matter of taste. - *Merge two existing dicts into a third, new dict*: This PEP proposes that the Obvious Way is to use the ``|`` merge operator. In practice, this preference for "only one way" is frequently violated in Python. For example, every ``for`` loop could be re-written as a ``while`` loop; every ``if`` block could be written as an ``if``/ ``else`` block. List, set and dict comprehensions could all be replaced by generator expressions. Document[2]: Date created: 19-Aug-2004 PEP: 20 Title: The Zen of Python Author: Tim Peters Status: Active Type: Informational Content-Type: text/x-rst Post-History: 22-Aug-2004 Abstract ======== Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. The Zen of Python ================= .. code-block:: text Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Easter Egg ========== .. code-block:: pycon >>> import this References ========== Originally posted to comp.lang.python/python-list@python.org under a thread called `"The Way of Python" `__ Copyright ========= This document has been placed in the public domain. Document[3]: Date created: 19-Aug-2004 The trio is not expected to preach/advertise for Python. They can if they want to, but not expected. - Not an educator of Python. The trio is not expected to be the ones teaching/writing about Python. They can if they want to, but not expected. - The trio is not expected to be available 24/7, 365 days a year. They are free to decide for themselves their availability for Python. - Not a PEP editor. Guidelines for the formation of the trio ======================================== The success of this governance model relies on the members of the trio, and the ability of the trio members to collaborate and work well together. The three people need to have similar vision to Python, and each can have different skills that complement one another. With such a team, disagreements and conflict should be rare, but can still happen. We will need to trust the people we select that they are able to resolve this among themselves. When it comes to select the members of the trio, instead of nominating various individuals and choosing the top three, core developers will nominate trios and vote for groups of threes who they believe can form this united trio. There is no restriction that an individual can only be nominated in one slate. This PEP will not name or nominate anyone into the trio. Only once this PEP is accepted, any active core developers (who are eligible to vote) can submit nomination of groups of three. Document[4]: Date created: 19-Aug-2004 Typically only exceptions that signal an error are desired to be caught. This means that exceptions that are used to signify that the interpreter should exit should not be caught in the common case. With KeyboardInterrupt and SystemExit moved to inherit from BaseException instead of Exception, changing bare ``except`` clauses to act as ``except Exception`` becomes a much more reasonable default. This change also will break very little code since these semantics are what most people want for bare ``except`` clauses. The complete removal of bare ``except`` clauses has been argued for. The case has been made that they violate both Only One Way To Do It (OOWTDI) and Explicit Is Better Than Implicit (EIBTI) as listed in the :pep:`Zen of Python <20>`. But Practicality Beats Purity (PBP), also in the Zen of Python, trumps both of these in this case. The BDFL has stated that bare ``except`` clauses will work this way [#python-dev8]_. Implementation deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- The compiler will emit the bytecode for ``except Exception`` whenever a bare ``except`` clause is reached. Transition Plan =============== Because of the complexity and clutter that would be required to add all features planned in this PEP, the transition plan is very simple. In Python |2.x| BaseException is added. In Python 3.0, all remaining features (required superclass, change in inheritance, bare ``except`` clauses becoming the same as ``except Exception``) will go into affect. Document[5]: Date created: 19-Aug-2004 * random_bytes - returns a random byte string. * random_number - depending on the argument, returns either a random integer in the range(0, n), or a random float between 0.0 and 1.0. * urlsafe_base64 - returns a random URL-safe Base64 encoded string. * uuid - return a version 4 random Universally Unique IDentifier. What Should Be The Name Of The Module? ====================================== There was a proposal to add a "random.safe" submodule, quoting the Zen of Python "Namespaces are one honking great idea" koan. However, the author of the Zen, Tim Peters, has come out against this idea [#]_, and recommends a top-level module. In discussion on the python-ideas mailing list so far, the name "secrets" has received some approval, and no strong opposition. There is already an existing third-party module with the same name [#]_, but it appears to be unused and abandoned. Frequently Asked Questions ========================== * Q: Is this a real problem? Surely MT is random enough that nobody can predict its output. A: The consensus among security professionals is that MT is not safe in security contexts. It is not difficult to reconstruct the internal state of MT [#]_ [#]_ and so predict all past and future values. There are a number of known, practical attacks on systems using MT for randomness [#]_. * Q: Attacks on PHP are one thing, but are there any known attacks on Python software? A: Yes. There have been vulnerabilities in Zope and Plone at the very least. Document[6]: Date created: 19-Aug-2004 If a developer knows that her package will never be a portion of a namespace package, then there is a performance advantage to it being a regular package (with an ``__init__.py``). Creation and loading of a regular package can take place immediately when it is located along the path. With namespace packages, all entries in the path must be scanned before the package is created. Note that an ImportWarning will no longer be raised for a directory lacking an ``__init__.py`` file. Such a directory will now be imported as a namespace package, whereas in prior Python versions an ImportWarning would be raised. Alyssa (Nick) Coghlan presented a list of her objections to this proposal [4]_. They are: 1. Implicit package directories go against the Zen of Python. 2. Implicit package directories pose awkward backwards compatibility challenges. 3. Implicit package directories introduce ambiguity into file system layouts. 4. Implicit package directories will permanently entrench current newbie-hostile behavior in ``__main__``. Alyssa later gave a detailed response to her own objections [5]_, which is summarized here: 1. The practicality of this PEP wins over other proposals and the status quo. 2. Minor backward compatibility issues are okay, as long as they are properly documented. 3. This will be https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.documented in :pep:`395`. 4. This will also be https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.documented in :pep:`395`. The inclusion of namespace packages in the standard library was motivated by Martin v. Löwis, who wanted the ``encodings`` package to become a namespace package [6]_. Document[7]: Date created: * A nearly-identical syntax is already established for f-strings. * Programmers will, as ever, adjust over time. The feature is confusing deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- We argue that: * Introducing new features typically has this impact temporarily. * The syntax is very similar to the established ``f'{x=}'`` syntax. * The feature and syntax are familiar from other popular modern languages. * The expansion of ``x=`` to ``x=x`` is in fact a trivial feature and inherently significantly less complex than ``*arg`` and ``**kwarg`` expansion. * This particular syntactic form has been independently proposed on numerous occasions, indicating that it is the most obvious [1]_ [2]_ [6]_. The feature is not explicit deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- We recognize that, in an obvious sense, the argument value is 'implicit' in this proposed syntax. However, we do not think that this is what the Zen of Python is aiming to discourage. In the sense that we take the Zen to be referring to, keyword arguments (for example) are more explicit than positional arguments where the argument name is omitted and impossible to tell from the local context. Conversely, the syntactic sugar for integers ``x += 1`` is not more implicit than ``x = x + 1`` in this sense, even though the variable is omitted from the right hand side, because it is immediately obvious from the local context what it is. Document[8]: Date created: 19-Aug-2004 - Provide vision and leadership for Python, the programming language and the community. - Understand their own limitation, and seek advice whenever necessary. - Provide mentorship to the next generation of leaders. - Be a Python core developer - Be a voting member of The PSF (one of Contributing / Manager / Fellow / Supporter). [2]_ - Understand that Python is not just a language but also a community. They need to be aware of issues in Python not just the technical aspects, but also other issues in the community. - Facilitate the formation of specialized working groups within Core Python. See "formation of specialized working groups" section below. - Set good example of behavior, culture, and tone to Python community. Just as Python looks at and learn from other communities for inspiration, other communities will look at Python and learn from us. Authority of the trio ===================== To be clear, in case any dispute arises: the trio has the final authority to pronounce on PEPs (except for the governance PEP), to decide whether a particular decision requires a PEP, and to resolve technical disputes in general. The trio's authority does not include changing the governance itself, or other non-technical disputes that may arise; these should be handled through the process described in :pep:`8001`. What are NOT considered as the role responsibilities of the trio ================================================================ The following are not the expected out of the trio, however they can do these if they wish. Question: what are the three zens of python? Answer: ``` For a complete list of `document`'s attributes, see [Haystack documentation](https://docs.haystack.deepset.ai/docs/data-classes#document).
## Adding Dates to Prompts You can use the Jinja2 time extension to insert dates in your prompts. ### Adding the Current Date You can use the `{% now %}` tag to render the current date and time in your prompts. The syntax is: `{% now [timezone] %}`. Type `/` in the prompt editor and choose *Now (Current Time)* to insert the tag. You can then choose the timezone and format of the date. For example: `The current time is: {% now 'CEST' %}`. This renders as: `The current time is 2025-05-06 17:03:12`. ### Storing the Date as a Variable Use the following syntax to set a variable name for the date: `The current time is {% now 'Europe/Berlin' as current_time %}`. `current_time` becomes the name of the variable for the current time. When using rich editor, simply type the variable name in the *As* field: ### Formatting the Date You can configure how the date is rendered in your prompts using `strftime`. When using rich editor, type the expected format in the *format* field. When using Jinja2 syntax: 1. Declare the current date as a variable. 2. Use `strftime` with this variable. For example, in this prompt template, we want the date to show in the following format: YYY-MM-DD HH:MM: ```yaml - content: - text: |- {% now 'Europe/Berlin' as current_time %} Session started at {{ current_time.strftime('%Y-%m-%d %H:%M') }} role: system - content: - text: Can you show me all events from {{ current_time }}? role: user ``` Here's a cheat sheet of useful format codes you can use with `strftime`: | Code | Meaning | Example | | ---- | ---------------------- | ------- | | %Y | Year (4 digits) | 2025 | | %y | Year (2 digits) | 25 | | %m | Month (01–12) | 05 | | %B | Full month name | May | | %b | Abbreviated month name | May | | %d | Day of the month | 06 | | %A | Full weekday name | Tuesday | | %a | Abbreviated weekday | Tue | | %H | Hour (24-hour clock) | 16 | | %I | Hour (12-hour clock) | 04 | | %p | AM/PM | PM | | %M | Minute | 47 | | %S | Second | 09 | | %z | UTC offset | \+0200 | | %Z | Timezone abbreviation | CEST | ## Examples ### Documents in Prompts :::info Make sure the component with the prompt template receives `documents` as input from the component that precedes it. ::: In RAG systems, you want the LLM to generate answers based on specific documents. You can pass these documents to the LLM by adding them as a variable in the prompt template. There are a couple of ways to do this. The simplest way is simply adding a `{{ documents }}` variable to your prompt, as in this example: ```jinja2 You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {{ documents }} Question: {{ question }} Answer: ``` This results in documents being passed to the LLM as one long string, often making it difficult to ground its answer in them.
Rendered prompt ```Text Rendered prompt You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: [Document(id=e307dd3c6f765aed116ad81d064dc8188d410481927309cd42b44ed8e22bb25e, content: '-------------------------- More Than One Way To Do It deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Okay, the Zen does...', meta: {'_split_overlap': [{'range': [1073, 1363], 'doc_id': '92d2764f063333fee7cf76d86254acb2752934ea07d2364c2b6eb209bb5cc739'}, {'range': [0, 223], 'doc_id': 'b44519a3df1ca77a0515c579ec00ad297dee50be90cb3eb3736e3716e80490c0'}], 'split_idx_start': 9309, 'file_name': 'pep-0584.txt', '_file_created_at': '2024-10-18T09:03:45.832385+00:00', 'split_id': 8, '_file_size': 30734, 'page_number': 1, 'file_id': '679bbf37-4cb9-4583-9f02-51289283bcd4', 'source_id': '982a93602209b5c2df80f37d9018d5a958aaf85e5f22a48e22d0f3970368d619'}, score: 0.158935546875), Document(id=a279b61737eef5529a0b27b2b97de0d4925c6509e8f00b1f37682a056371e50b, content: 'PEP: 20 Title: The Zen of Python Author: Tim Peters Status: Active Type: Info...', meta: {'_split_overlap': [], 'split_idx_start': 0, 'file_name': 'pep-0020.txt', '_file_created_at': '2024-10-18T09:04:17.099685+00:00', 'split_id': 0, '_file_size': 1673, 'page_number': 1, 'file_id': '66633e10-67b1-4210-ab81-f22b162da69f', 'source_id': 'd4398d899e10248f3615dfc523283ebdd06cc9d4ba7349bc2dfc0dabc7310e9f'}, score: 0.132568359375), Document(id=92d2764f063333fee7cf76d86254acb2752934ea07d2364c2b6eb209bb5cc739, content: 'If one expects to be merging a large number of dicts where performance is an issue, it may be better...', meta: {'_split_overlap': [{'range': [1172, 1531], 'doc_id': 'c6070df4a665dea988466251522ab286451f86e8d67e821484365fbe860dc522'}, {'range': [0, 290], 'doc_id': 'e307dd3c6f765aed116ad81d064dc8188d410481927309cd42b44ed8e22bb25e'}], 'split_idx_start': 8236, 'file_name': 'pep-0584.txt', '_file_created_at': '2024-10-18T09:03:45.832385+00:00', 'split_id': 7, '_file_size': 30734, 'page_number': 1, 'file_id': '679bbf37-4cb9-4583-9f02-51289283bcd4', 'source_id': '982a93602209b5c2df80f37d9018d5a958aaf85e5f22a48e22d0f3970368d619'}, score: 0.04217529296875), Document(id=de665889f31c7e28b722106a5fa445dea020cb5b1deadb5ff87a200dccbca64b, content: '* A nearly-identical syntax is already established for f-strings. * Programmers will, as ever, adjus...', meta: {'_split_overlap': [{'range': [1300, 1547], 'doc_id': 'cbda35aa73c0e994987f1df6aa33996b3e6bfee5d37fe00b43c74a3389dcb78d'}, {'range': [0, 243], 'doc_id': '855465dc4e9941a1b50d267d7f23d61378288a60c87769ea2fe3a4e01d42fdb8'}], 'split_idx_start': 16006, 'file_name': 'pep-0736.txt', '_file_created_at': '2024-10-18T09:03:32.851485+00:00', 'split_id': 10, '_file_size': 25013, 'page_number': 1, 'file_id': 'a5a73fe5-14e4-43e0-8839-104d658a268d', 'source_id': '6acf4d46895d82a5b5f39ef3a4b8bb7b602ad6751d97fc5ea7ae5bb80a7ef869'}, score: 0.033599853515625), Document(id=dcbacf054847b57d03e5a03d8220d99451fa8ae0e7fbcc9c181d6c9a6daf6103, content: 'Type declarators after names that are only read, not assigned to, are not strictly necessary but enf...', meta: {'_split_overlap': [{'range': [1335, 1565], 'doc_id': '8462f7bf34aa29a6abd2b0967902c5f8ff40845458c887616d9b271acf898cb3'}, {'range': [0, 375], 'doc_id': '8ca6c53419aaf4828c9c399dea7c87ef77b78ad770be79cdc7b1de7915f2ad7a'}], 'split_idx_start': 2713, 'file_name': 'pep-3117.txt', '_file_created_at': '2024-10-18T09:03:32.119394+00:00', 'split_id': 2, '_file_size': 8570, 'page_number': 1, 'file_id': '28215f42-588c-4a05-bb30-d38a979e54b9', 'source_id': '0098114fc233fd584f7b3dce6f20b38f8fee5671534fcadf52609771eb1872d9'}, score: 0.029205322265625), Document(id=266460ca840d425453afcbcb214b775de933f816972f4294c2992f911743ea3a, content: '* random_bytes - returns a random byte string. * random_number - depending on the argument, retur...', meta: {'_split_overlap': [{'range': [1633, 1826], 'doc_id': 'cb505fb7b551acc17bc30be7e4698eca6ce01f2724326b7b8a38cfc1eaabba27'}, {'range': [0, 173], 'doc_id': '6754d08c1a7fb48d16d754bc556a76f6b049c977640b0bb130d723348134d74c'}], 'split_idx_start': 10795, 'file_name': 'pep-0506.txt', '_file_created_at': '2024-10-18T09:03:53.308697+00:00', 'split_id': 8, '_file_size': 18395, 'page_number': 1, 'file_id': '13775073-db35-4864-b7fc-a1d71202be3a', 'source_id': '375ba446b3fc8643ef846664ea0f644caba318a6d0fb7113475c3dbf7357e906'}, score: 0.028594970703125), Document(id=8462f7bf34aa29a6abd2b0967902c5f8ff40845458c887616d9b271acf898cb3, content: 'Therefore, this PEP combines the move to type declarations with another bold move that will once aga...', meta: {'_split_overlap': [{'range': [1378, 1629], 'doc_id': '1f47efdb3224a877cf94bcbee759cf79b96f83768dc99bbc301b2a2f9cbd1417'}, {'range': [0, 230], 'doc_id': 'dcbacf054847b57d03e5a03d8220d99451fa8ae0e7fbcc9c181d6c9a6daf6103'}], 'split_idx_start': 1378, 'file_name': 'pep-3117.txt', '_file_created_at': '2024-10-18T09:03:32.119394+00:00', 'split_id': 1, '_file_size': 8570, 'page_number': 1, 'file_id': '28215f42-588c-4a05-bb30-d38a979e54b9', 'source_id': '0098114fc233fd584f7b3dce6f20b38f8fee5671534fcadf52609771eb1872d9'}, score: 0.0258636474609375), Document(id=0358e0dc28ffad1c66d8b51e8b52c87670bb10d3379df9ca215c94f00dcbf881, content: 'Typically only exceptions that signal an error are desired to be caught. This means that exceptions...', meta: {'_split_overlap': [{'range': [1441, 1642], 'doc_id': '2b91fca3faf02123a3d14f6aa206cfec9848a40577a72561e43b9d45a42947da'}, {'range': [0, 384], 'doc_id': 'd8038333a8193db3f52139147c1dd0fc38b13099a86a14ff05c9ca28c7641cc8'}], 'split_idx_start': 9260, 'file_name': 'pep-0348.txt', '_file_created_at': '2024-10-18T09:04:05.356969+00:00', 'split_id': 7, '_file_size': 19534, 'page_number': 1, 'file_id': '96d69bd9-9727-4ad0-a06e-ddafb8d96c0d', 'source_id': 'e6bf6cb76eed041b0d80c64c9bf0898d7017757b0933dbed1e1a54a05f079a83'}, score: 0.010650634765625)] ```
### Changing How the Documents Are Presented You can also use a Jinja loop to add documents to your prompts. The following loop structures documents in a numbered way: ```jinja2 These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: ``` This loop results in documents being rendered like this: ``` Document[1]: Document[2]: ``` Such a format makes it easier for the LLM to understand document boundaries by creating a clear, predictable structure. It's also useful if you want the LLM to generate references in its answers. It can then reference the document by its number.
Rendered prompt example ``` You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: Document[1]: deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- More Than One Way To Do It deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Okay, the Zen doesn't say that there should be Only One Way To Do It. But it does have a prohibition against allowing "more than one way to do it". ''''''''Response '''''''' There is no such prohibition. The "Zen of Python" merely expresses a *preference* for "only one *obvious* way":: There should be one-- and preferably only one --obvious way to do it. The emphasis here is that there should be an obvious way to do "it". In the case of dict update operations, there are at least two different operations that we might wish to do: - *Update a dict in place*: The Obvious Way is to use the ``update()`` method. If this proposal is accepted, the ``|=`` augmented assignment operator will also work, but that is a side-effect of how augmented assignments are defined. Which you choose is a matter of taste. - *Merge two existing dicts into a third, new dict*: This PEP proposes that the Obvious Way is to use the ``|`` merge operator. In practice, this preference for "only one way" is frequently violated in Python. For example, every ``for`` loop could be re-written as a ``while`` loop; every ``if`` block could be written as an ``if``/ ``else`` block. List, set and dict comprehensions could all be replaced by generator expressions. Document[2]: PEP: 20 Title: The Zen of Python Author: Tim Peters Status: Active Type: Informational Content-Type: text/x-rst Created: 19-Aug-2004 Post-History: 22-Aug-2004 Abstract ======== Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. The Zen of Python ================= .. code-block:: text Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Easter Egg ========== .. code-block:: pycon >>> import this References ========== Originally posted to comp.lang.python/python-list@python.org under a thread called `"The Way of Python" `__ Copyright ========= This document has been placed in the public domain. Document[3]: If one expects to be merging a large number of dicts where performance is an issue, it may be better to use an explicit loop and in-place merging:: new = {} for d in many_dicts: new |= d deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Dict Union Is Lossy deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Dict union can lose data (values may disappear); no other form of union is lossy. ''''''''Response '''''''' It isn't clear why the first part of this argument is a problem. ``dict.update()`` may throw away values, but not keys; that is expected behavior, and will remain expected behavior regardless of whether it is spelled as ``update()`` or ``|``. Other types of union are also lossy, in the sense of not being reversible; you cannot get back the two operands given only the union. ``a | b == 365``... what are ``a`` and ``b``? deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Only One Way To Do It deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Dict union will violate the Only One Way koan from the Zen. ''''''''Response '''''''' There is no such koan. "Only One Way" is a calumny about Python originating long ago from the Perl community. deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- More Than One Way To Do It deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- Okay, the Zen doesn't say that there should be Only One Way To Do It. But it does have a prohibition against allowing "more than one way to do it". ''''''''Response '''''''' There is no such prohibition. Document[4]: * A nearly-identical syntax is already established for f-strings. * Programmers will, as ever, adjust over time. The feature is confusing deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- We argue that: * Introducing new features typically has this impact temporarily. * The syntax is very similar to the established ``f'{x=}'`` syntax. * The feature and syntax are familiar from other popular modern languages. * The expansion of ``x=`` to ``x=x`` is in fact a trivial feature and inherently significantly less complex than ``*arg`` and ``**kwarg`` expansion. * This particular syntactic form has been independently proposed on numerous occasions, indicating that it is the most obvious [1]_ [2]_ [6]_. The feature is not explicit deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- We recognize that, in an obvious sense, the argument value is 'implicit' in this proposed syntax. However, we do not think that this is what the Zen of Python is aiming to discourage. In the sense that we take the Zen to be referring to, keyword arguments (for example) are more explicit than positional arguments where the argument name is omitted and impossible to tell from the local context. Conversely, the syntactic sugar for integers ``x += 1`` is not more implicit than ``x = x + 1`` in this sense, even though the variable is omitted from the right hand side, because it is immediately obvious from the local context what it is. Document[5]: Type declarators after names that are only read, not assigned to, are not strictly necessary but enforced anyway (see the Python Zen: "Explicit is better than implicit."). The mapping between types and declarators is not static. It can be completely customized by the programmer, but for convenience there are some predefined mappings for some built-in types: ========================= =================================================== Type Declarator ========================= =================================================== ``object`` � (REPLACEMENT CHARACTER) ``int`` ℕ (DOUBLE-STRUCK CAPITAL N) ``float`` ℮ (ESTIMATED SYMBOL) ``bool`` ✓ (CHECK MARK) ``complex`` ℂ (DOUBLE-STRUCK CAPITAL C) ``str`` ✎ (LOWER RIGHT PENCIL) ``unicode`` ✒ (BLACK NIB) ``tuple`` ⒯ (PARENTHESIZED LATIN SMALL LETTER T) ``list`` ♨ (HOT SPRINGS) ``dict`` ⧟ (DOUBLE-ENDED MULTIMAP) ``set`` ∅ (EMPTY SET) (*Note:* this is also for full sets) ``frozenset`` ☃ (SNOWMAN) ``datetime`` ⌚ (WATCH) ``function`` ƛ (LATIN SMALL LETTER LAMBDA WITH STROKE) ``generator`` ⚛ (ATOM SYMBOL) ``Exception`` ⌁ (ELECTRIC ARROW) ========================= =================================================== The declarator for the ``None`` type is a zero-width space. These characters should be obvious and easy to remember and type for every programmer. Unicode replacement units ========================= Since even in our modern, globalized world there are still some old-fashioned rebels who can't or don't want to use Unicode in their source code, and since Python is a forgiving language, a fallback is provided for those: Instead of the single Unicode character, they can type ``name${UNICODE NAME OF THE DECLARATOR}$``. Document[6]: * random_bytes - returns a random byte string. * random_number - depending on the argument, returns either a random integer in the range(0, n), or a random float between 0.0 and 1.0. * urlsafe_base64 - returns a random URL-safe Base64 encoded string. * uuid - return a version 4 random Universally Unique IDentifier. What Should Be The Name Of The Module? ====================================== There was a proposal to add a "random.safe" submodule, quoting the Zen of Python "Namespaces are one honking great idea" koan. However, the author of the Zen, Tim Peters, has come out against this idea [#]_, and recommends a top-level module. In discussion on the python-ideas mailing list so far, the name "secrets" has received some approval, and no strong opposition. There is already an existing third-party module with the same name [#]_, but it appears to be unused and abandoned. Frequently Asked Questions ========================== * Q: Is this a real problem? Surely MT is random enough that nobody can predict its output. A: The consensus among security professionals is that MT is not safe in security contexts. It is not difficult to reconstruct the internal state of MT [#]_ [#]_ and so predict all past and future values. There are a number of known, practical attacks on systems using MT for randomness [#]_. * Q: Attacks on PHP are one thing, but are there any known attacks on Python software? A: Yes. There have been vulnerabilities in Zope and Plone at the very least. Document[7]: Therefore, this PEP combines the move to type declarations with another bold move that will once again prove that Python is not only future-proof but future-embracing: the introduction of Unicode characters as an integral constituent of source code. Unicode makes it possible to express much more with much less characters, which is in accordance with the :pep:`Zen <20>` ("Readability counts."). Additionally, it eliminates the need for a separate type declaration statement, and last but not least, it makes Python measure up to Perl 6, which already uses Unicode for its operators. [#]_ Specification ============= When the type declaration mode is in operation, the grammar is changed so that each ``NAME`` must consist of two parts: a name and a type declarator, which is exactly one Unicode character. The declarator uniquely specifies the type of the name, and if it occurs on the left hand side of an expression, this type is enforced: an ``InquisitionError`` exception is raised if the returned type doesn't match the declared type. [#]_ Also, function call result types have to be specified. If the result of the call does not have the declared type, an ``InquisitionError`` is raised. Caution: the declarator for the result should not be confused with the declarator for the function object (see the example below). Type declarators after names that are only read, not assigned to, are not strictly necessary but enforced anyway (see the Python Zen: "Explicit is better than implicit."). The mapping between types and declarators is not static. Document[8]: Typically only exceptions that signal an error are desired to be caught. This means that exceptions that are used to signify that the interpreter should exit should not be caught in the common case. With KeyboardInterrupt and SystemExit moved to inherit from BaseException instead of Exception, changing bare ``except`` clauses to act as ``except Exception`` becomes a much more reasonable default. This change also will break very little code since these semantics are what most people want for bare ``except`` clauses. The complete removal of bare ``except`` clauses has been argued for. The case has been made that they violate both Only One Way To Do It (OOWTDI) and Explicit Is Better Than Implicit (EIBTI) as listed in the :pep:`Zen of Python <20>`. But Practicality Beats Purity (PBP), also in the Zen of Python, trumps both of these in this case. The BDFL has stated that bare ``except`` clauses will work this way [#python-dev8]_. Implementation deepset_platform_metadata: group: how-tos navigation: guides section: working-with-llms source: docusaurus-build title: writing-prompts-in-deepsetq type: how-to --- The compiler will emit the bytecode for ``except Exception`` whenever a bare ``except`` clause is reached. Transition Plan =============== Because of the complexity and clutter that would be required to add all features planned in this PEP, the transition plan is very simple. In Python |2.x| BaseException is added. In Python 3.0, all remaining features (required superclass, change in inheritance, bare ``except`` clauses becoming the same as ``except Exception``) will go into affect. Question: what are the python zens? Answer: ```
#### Adding Documents with Their Metadata You can also enhance the documents passed to the LLM with their metadata by using this syntax: `document.meta.`. This example adds the date of publication and genre of each document in the prompt: ```jinja2 Here are the articles: {% for document in documents %} Document[{{ loop.index }}]: Date of Publication: {{ document.meta.date }} Genre: {{ document.meta.genre }} {{ document.content }} {% endfor %} Question: {{ question }} Answer: ``` In the rendered prompt, the documents would be displayed as follows: ``` Here are the articles: Document[1]: Date of Publication: 12.03.2024} Genre: News This is a news article. Document[2]: Date of Publication: 23.09.2024} Genre: Interview This is an interview. Question: What happened in Austria yesterday? Answer: ``` ### Examples in Prompts You can add examples to your prompt. This technique, called few-shot prompting, teaches the LLM how to perform the task by example. This prompt contains examples of questions and answers: ```jinja2 You are a helpful assistant that answers questions. Answer the questions as shown in the examples. Here are some question-answer examples: {% set ns = namespace(example="") -%} {% for e in examples -%} {% set ns.example = ns.example + "\nQuery: " + e.query + "\nResponse: "+ e.response + "\n" -%} {% endfor -%} {{ ns.example }} Now please answer the user query. Query: {{query}} Answer: ``` :::info In this case, PromptBuilder would need `examples` and `query` as input to render the prompt. ::: The rendered prompt would contain some query-response pairs: ``` You are a helpful assistant that answers questions Answer the questions as shown in the examples. Here are some question-answer examples: Query: What is the capital of France? Response: The capital of France is Paris. Query: How tall is Mount Everest? Response: Mount Everest is approximately 29,029 feet (8,848 meters) tall. Now please answer the user query. Query: What is the speed of light? Answer: ``` ### Variables in Prompts #### Setting Required Variables This `ChatPromptBuilder`'s prompt contains the `target_language` and `text` variables. Then, using the `required_variables` setting, it declares them as required. This means that if either of them is not provided at runtime, the component raises an error. `ChatPromptBuilder` template: ```yaml - content: text: "Translate to {{ target_language }}: {{ text }}" role: user ``` `ChatPromptBuilder` `required_variables` parameter setting to indicate both variables are required: ```yaml - target_language - text ``` #### Declaring All Variables The following prompts declare all variables as valid inputs and set `location` and `day_count` as required. This is the system prompt: ```text You are a helpful assistant speaking {{ language }} ``` This is the user prompt: ```text "What’s the weather in {{ location }} for the next {{ day_count }} days?" ``` Then, in Required Variables, you indicate which of the variables must be provided: ```yaml - location - day_count ``` --- ## Collect User Feedback Monitor users' feedback to give you an indication of how your AI system is doing. Collecting feedback is crucial throughout your app's lifecycle to evaluate quality and improve the pipeline, starting from development, through prototype testing, to production. ## About This Task You or your users can rate each answer as accurate (thumbs up), fairly accurate (thumbs sideways), or inaccurate (thumbs down). When users select the rating, they can explain it by selecting predefined reasons called tags or by adding comments in the text field. Admins can add feedback tags to a pipeline through the Pipeline Details page or REST API endpoints. Users can then select applicable tags when rating an answer. Tags can then help classify feedback entries: Before moving your pipeline to production, you can share its prototype and let the users test it. For information on how to do this, see [Share a Pipeline Prototype](./share-a-pipeline-prototype.mdx). ## Setting Up a Feedback System in Production Collect feedback from your users to monitor your pipeline's performance over time, identify potential issues (such as data drift), or use it to improve your pipeline. To collect feedback: 1. Add tags you want your users to select when assigning ratings to answers. Tags are specific to a pipeline. To add tags in : 1. Go to _Pipelines_ and click the name of the pipeline you want to add tags to. This opens the Builder. 2. Switch to _Settings_ and add feedback tags. 2. Add the "thumbs" buttons and a text field in your UI. 3. Send requests with the feedback to 's [Create Feedback](/docs/api/main/create-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-post.api.mdx) API endpoint. If you're using the UI, the feedback system is added to each pipeline by default. You just need to add tags to your pipeline, if needed. ## Analyzing Feedback You can analyze feedback on the Analytics tab: 1. On the Pipelines page, click the name of the pipeline whose feedback you want to view. 2. When you're in Builder, switch to **Analytics**. 2. Go to **History**. 3. Use Feedback Insights to analyze feedback patterns and generate executive summaries to help you understand performance trends and identify areas for improvement. You can start with one of the suggested prompts or enter your own query. Based on the prompt, AI analyzes your pipeline activity and generates a summary. 4. In the table, go to **Manage Table Preferences** and enable columns related to feedback, like Feedback Rating, Feedback Notes, and Feedback Tags. You can then add notes and hashtags to your queries using these columns in the table. You can also analyze feedback programmatically with [Get Paginated Feedback](/docs/api/main/get-paginated-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-get.api.mdx) (returns detailed feedback), [Get Pipeline Feedback Stats](/docs/api/main/get-pipeline-feedback-stats-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-stats-get.api.mdx) (returns feedback statistics, like the count of entries, users, and average accuracy), and [Export Feedback](/docs/api/main/export-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-export-get.api.mdx) (downloads a CSV file with all feedback). ## Related Information - [Share a Pipeline Prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx) - [Evaluating Step-by-Step](/docs/how-to-guides/evaluating-your-pipeline/evaluating-your-pipeline.mdx) --- ## Evaluating Step-by-Step ## Why Should I Evaluate? Before bringing your pipeline to production, you want to make sure it's useful, provides relevant results, and serves the intended purpose. By evaluating your app, you can determine how effective it is and how satisfied the users are. You can share your pipeline prototype with external users and collect their feedback in interface. Prototypes are customizable, you can add your brand logo and colors to them. ## Detailed Steps Here’s a breakdown of the steps we recommend you take to evaluate your pipeline: 1. [Upload files to your workspace](/docs/how-to-guides/working-with-your-data/upload-files.mdx). The pipeline you’re evaluating will run on these files. The more files you upload, the more difficult the task of finding the right answer is. 2. [Create a pipeline](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). You can start with one of the ready-made templates. 3. [Share your pipeline with users](./share-a-pipeline-prototype.mdx). At this stage, you want to get an idea of how people use your pipeline and if it works OK. You’re not aiming for high user satisfaction at this point. You just want to determine if it’s ready for an evaluation through experiments. If most of your users are happy with the results, it means it’s good to go. Otherwise, try tweaking your app until its performance is satisfactory. 4. [Collect user feedback](./collect-feedback.mdx). It's best to have domain experts and qualified users try your pipeline and then use their feedback to improve it. 5. [Optimize and improve your pipeline](/docs/how-to-guides/optimizing-your-pipeline/improving-your-qa-pipeline.mdx). --- ## Export Users' Feedback When trying out your pipeline, users can give feedback for each answer. You can export this feedback into a CSV file. ## Export Feedback from the UI 1. Log in to and go to _Pipelines_. 2. Find the pipeline whose feedback you want to export, click the more actions icon next to it, and choose **Export feedback**. 3. Choose _Export feedback_. This downloads the CSV file to your computer. ## Export Feedback with REST API You need to [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) first. Use the [Get Pipeline Feedback](/docs/api/main/get-pipeline-feedback-stats-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-stats-get.api.mdx) endpoint. Here's the code to export the feedback: ```curl curl --request GET \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines//feedback \ --header 'accept: text/csv' \ --header 'authorization: Bearer ' ``` --- ## Guidelines for Onboarding Your Users To demo your application to the users, it is important to explain how it works and to set the right expectations. Here are a couple of guidelines that can help you do it. ## Basic Search Functionality Make sure the users know what to expect from your system. For example: - For extractive question answering systems that highlight the answer in the text, make sure the users understand that the information they're looking for must exist in the text data the system runs on. The search system cannot make up answers by itself. - For generative question answering pipelines that aren't chat, make sure the users realize it's not chat-based. The system generates novel answers, but they're unrelated to the previous question. - What the system returns depends on the pipeline you defined. For example, for a Retriever-only pipeline, the system returns text passages that fit the query, while for a question answering pipeline, the system also highlights the answers within the text passages it returns. Make sure your users know this. - Explain what queries work well (for example, natural language questions as opposed to simple keywords or copy-pasted error messages). ## Data - Make your users aware of what data is indexed in their search application. This is the data the system searches. For example, if your system runs on an internal company database, it can answer questions about information in this database. It won't work for questions from other domains. - Make sure your users understand that if they ask for information about documents that don't exist in , the system won't be able to find an answer. ## Relevance Scores - Extractive question answering add relevance scores to answers. Make sure your users understand the relevance scores displayed beneath each model prediction. - Set the right threshold for the relevance scores if some users might be confused by model predictions with very low relevance. ## Feedback - To collect users' feedback, ask them to click thumbs up or thumbs down for each answer. User feedback helps in evaluating and improving your pipeline. It lets you see the types of questions the model struggles with. See [Collect User Feedback](./collect-feedback.mdx) for more details. :::tip Evaluating Pipeline Results We recommend that you instruct the users that they shouldn't be too strict about the results. If a result helps to answer their question, ask them to select the thumbs-up icon. This includes answers that, for example, lack a word or have the whole sentence highlighted even though just a part of it would be enough. If a result is garbage text, completely false, or not helpful at all, they should use the thumbs-down icon. ::: --- ## Share a Pipeline Prototype When you have a deployed pipeline, you can generate a link to it and send it to anyone you think should try your pipeline. By letting real users test your pipeline, you can get an idea of how it performs. ## About this Task You can make your prototype accessible to anyone with the link, without needing to set up accounts, or you can restrict access to people in your organization. ### What Am I Sharing? Users with access to your prototype can: - View a read-only prototype page. - Run searches on your pipeline and add feedback to search results. - Share the prototype link. They cannot edit or change anything in . They gain read-only access to the Search page that uses your pipeline and to the following assets: - File metadata from the search if you enable metadata filters. - Documents returned from the search. - Document metadata from the search. - The name of the pipeline you shared. - Any metadata for your pipeline in the document store if you enable the metadata filters for the prototype. If a user without a account or not logged in to opens a shared pipeline link, they only see that specific pipeline. If a logged-in user opens the same link, they see all the deployed pipelines in the workspace they have access to. ### Prototypes With Login Required If you configure the prototype to require login, a user must be a member of your organization to view the prototype. They'll be requested to log in when they paste the link into the browser window. ### Prototype Lifespan When sharing a pipeline prototype, you can specify when the link to your prototype should expire. If you want to stop sharing the prototype, you can do so at any time by simply deleting the generated link. ### Prototype Style Use the **Style** tab in the Share prototype window to customize your prototype look and feel. Add a brand logo and colors. Here's what a customized prototype where users can view source documents may look like: ### Do the Users Need a Account? If the prototype is not set to require login, anyone with the prototype link can use the pipeline right away. They don't need to create or have a account. ### Collecting Feedback When testing your pipeline, users can provide feedback on the answers the pipeline returns. You can then view this feedback on the pipeline details page or [export it](./export-users-feedback.mdx) to a file. Feedback can show you how to optimize your pipeline for better performance. ### Updating a Shared Pipeline If you find you want to change the pipeline you already shared, you can edit it at any time. You'll need to undeploy the pipeline, change it, and then deploy it again. The sharing link stays the same, so all you need to do is let your users know the pipeline may not work until it's deployed again. ## Prerequisites - Your pipeline must be [deployed](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx) and active so that users can run queries with it and test it out. - Set the right expectations for your users. For tips on doing this, see [Guidelines for Onboarding Your Users](./guidelines-for-onboarding-your-users.mdx). ## Share Your Prototype 1. In , click **Pipelines**. 2. Find the pipeline you want to share, and click **Share** next to it. A window with prototype settings opens. 3. On the **Settings** tab: 1. Set the link expiration time. 2. Add any notes to your users. These can be guidelines on how to use the prototype, things they should pay attention to, and so on. These notes are shown on the prototype page the users open with your link. 3. Decide if the prototype requires login. If you enable this option, only users from your organization will be able to use the prototype after they log in. 3. Decide if you want to enable metadata filters. These are the metadata in your documents. They act as search filters. 4. Choose if you want the users to be able to see the source documents. 4. Optionally, on the **Style** tab, upload your logo and choose your brand colors. Your logo shows in the bottom left corner of the shared prototype, and your color is used to highlight the generated answer. 5. Generate and copy the link. You can now send it to anyone you like. ## Stop Sharing a Prototype You can revoke access to your prototype by simply deleting the link. To do this: 1. In , click **Pipelines**. 2. Find the pipeline you want to stop sharing, click the more actions menu next to it, and choose _Share_. 3. Click **Delete link**. When you delete the link, nobody can access the prototype anymore. You need to generate a new link to share the prototype again. --- ## Add Custom Model Definitions Configure custom model configurations to use in your pipelines. Custom models let you define YAML configurations for models and reuse them across pipelines. *** ## About This Task With custom models, you can: - Use models from providers beyond the standard integrations. - Configure model parameters and generation settings for your use case. - Create reusable model configurations for your organization or workspace. - Set custom API endpoints and authentication methods. A custom model definition is a reusable configuration for a model. It can include a specific model, its parameters, or both. For example, you can define an OpenAI model with custom parameters and reuse it across multiple pipelines. After you save a custom model, it appears in the list of available models on components that support models, such as `LLM` or `Agent`. You can create custom models at two levels: - Workspace: Available only in the current workspace. - Organization: Available across all workspaces in your organization. ## Prerequisites - You must be an organization Admin to add custom model definitions for an organization, or have write access to a workspace to add custom model definitions to a workspace. - You must have a valid API key from the model provider. ## Add a Custom Model Definition 1. In , click your profile icon and choose _Settings_. 2. Go to _Organization>Integrations_ (for organization-level custom models) or _Workspace>Integrations_ (for workspace-level custom models). 3. Find *Custom Models* and click **Configure**. 4. Click **Add model**. 5. Enter the following details: - *Model name*: A descriptive name for your custom model - *Provider*: Pick the model provider from the list. For a provider that is not listed, choose **Custom**. 6. Configure the YAML settings: - Chat Generator: Define the component configuration including API endpoints and authentication. - Model Parameters: Specify model parameters, like temperature and max output tokens. These parameters are specific to the model provider you choose. Check the model provider's documentation for allowed parameters. 7. Optionally, try the model to check if the configuration is working. 7. Save your changes. ## Use Custom Models in Pipelines :::info Custom Models Are Copied Into Pipelines When you add a custom model to your pipeline, it creates a copy of that model. This means any changes you make to the model definition on the Integrations page do not affect the model in your pipeline. To update the model in your pipeline, edit the pipeline YAML configuration. ::: After creating a custom model definition, you can use it in your pipelines by choosing it from a list of available models when configuring AI components, like `LLM` or `Agent`. The model is shown alongside standard models in component configuration. ## Manage Custom Models You can update or delete custom model definitions. Changes you make to the model definition do not affect the model in your pipelines. To update the model in your pipeline, edit the pipeline YAML configuration. 1. On the Integrations page, click **Configure** on the Custom Models Card. All custom model definitions are listed here. 2. Click **Edit** next to the model definition you want to update, or **Delete** to remove it. ## Related Information - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) - [Agent](/docs/reference/pipeline-components/ai/Agent.mdx) --- ## Add Integrations Connect to model or service providers, such as Hugging Face, Open AI, Cohere, or https://unstructured.io/. This lets you use their models or data processing services in your pipelines and indexes. *** ## About This Task Adding an integration connects with an external model or service provider. Once connected, you can use their services directly in your pipeline components, without passing the API key in the component's configuration. For more information on integrations, see [Secrets and Integrations](/docs/concepts/secrets-and-integrations.mdx). To standardize model configuration for reuse across pipelines, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ### Integration Scope You can add integrations at either the workspace or organization level: - Workspace-level integrations are available only to pipelines and indexes within that specific workspace. - Organization-level integrations are available to all workspaces in the organization. If the same provider is integrated at both levels, the workspace-level integration takes priority. ### Providers ### Prerequisites - Make sure you have an active account with the provider. - Have your API key or access credentials ready. For help getting credentials, see: - [User access tokens in Hugging Face](https://huggingface.co/docs/hub/security#user-access-tokens). - [Secret API keys in Open AI](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key) - [Production keys in co:here](https://docs.cohere.ai/docs/going-live#production-key-specifications) - [Model access in Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) - [Getting access to Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/faq#getting-access-to-azure-openai-service) - [Getting an API key for Gemini API](https://ai.google.dev/gemini-api/docs/api-key) - [Nvidia personal keys](https://org.ngc.nvidia.com/setup/personal-keys) - [Using Document Intelligence models](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/how-to-guides/use-sdk-rest-api?view=doc-intel-4.0.0&tabs=windows&pivots=programming-language-csharp) - [DeepL API](https://www.deepl.com/en/products/api) - [Snowflake website](https://www.snowflake.com/de/) - [unstructured.io documentation](https://docs.unstructured.io/welcome) - [Google Search API](https://www.searchapi.io/) - [VoyageAI](https://www.voyageai.com/) - [MongoDB: Create an API key](https://www.mongodb.com/docs/cloud-manager/reference/api/api-keys/org/create-one-org-api-key/) - [together.ai Quickstart](https://docs.together.ai/docs/quickstart) - [Weights & Biases: How do I find my API key](https://docs.wandb.ai/support/find_api_key/) ## Connect to a Provider --- ## Add Secrets Secrets securely manage sensitive information, such as API keys, and allow connections to third-party service providers that require authentication. They're especially useful for handling development and production API keys or when building custom components that need to authenticate with a third-party provider. *** ## About This Task Secrets let you connect to providers not listed on the Integrations page. You can also use them for custom components or to manage production and development API keys. For more information about secrets, see [Secrets and Integrations](/docs/concepts/secrets-and-integrations.mdx). ### Secret Scope You can add secrets at either the workspace or organization level: - Workspace-level secrets are available only to pipelines and indexes within that specific workspace. - Organization-level secrets are available to all workspaces in the organization. If the same provider is integrated at both levels, the workspace-level integration takes priority. ## Prerequisites - Make sure you have an active account with the provider. - Have your API key or access credentials ready. - For existing components: Check the component's documentation to find the environment variable it uses to read the API key. - For custom components: In your component's code, define and environment variable to store the API key. Then, create a secret with he same name. ## Connect to a Provider ### Use the Secret in Your Custom Components Add the secret to your component's code: - Make sure you import it. - Specify the environment variable name, which must match the secret's name. - Add its serialization and deserialization methods. - Add a `warm_up()` method to load the API key before pipeline validation. This step is optional but we recommend it: ```python from haystack import component, default_from_dict, default_to_dict from haystack.utils import Secret, deserialize_secrets_inplace from typing import Any, Dict @component class MyComponent: def __init__(self, model_name: str, api_key: Secret = Secret.from_env_var("ENV_VAR_NAME")): self.model_name = model_name self.api_key = api_key self.backend = None def warm_up(self): # Call api_key.resolve_value() to load the API key from the environment variable # We put the resolution in warm_up() to avoid loading the API key during pipeline validation if self.backend is None: self.backend = SomeBackend(self.model_name, self.api_key.resolve_value()) def to_dict(self) -> Dict[str, Any]: # Make sure to include any other init parameters in the to_dict method return default_to_dict( self, model_name=self.model_name, api_key=self.api_key.to_dict(), ) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MyComponent": # Make sure to use deserialize_secrets_inplace to load the Secret object init_params = data.get("init_parameters", {}) deserialize_secrets_inplace(init_params, keys=["api_key"]) return default_from_dict(cls, data) def run(self, my_input: Any): if self.backend is None: raise RuntimeError("The component wasn't warmed up. Run 'warm_up()' before calling 'run()'.") return self.backend.process(my_input) ``` If you have multiple secrets for one provider, you can easily switch between them in your pipeline YAML by updating the secret's name: ```yaml llm: type: dc_custom_component.components.my_components.component1.MyComponent # the path to your component init_parameters: api_key: {"type": "env_var", "env_vars": ["ENV_VAR_NAME"], "strict": False} # uses the `ENV_VAR_NAME` secret # to use another secret, update its name here ``` --- ## Add Users to Organization Invite users to your organization to grant them access to individual workspaces. *** ## About This Task Before you can grant users access to workspaces, you must first invite them to your organization. When you send an invitation, the user receives an email with a link to set up their login and password. # Invite Users 1. Click your profile icon and choose _Settings_. 2. Go to _Organization_. 3. Open _Members_ and click **Invite Member.** 4. Enter the user's email https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.document. You can click **Invite** now to add the user to the organization without granting them permissions to any workspaces. 5. To add the user to workspaces within the organization: 1. Click **More Options**. 2. Choose the workspace and role for the user. The role defines user permissions for the workspace. For details, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). 6. Click **Invite**. :::tip Managing Users in Workspaces You can update user roles in workspaces later in Workspace settings from the **Members** tab. --- ## Connect to Model and Service Providers --- ## Create Custom Roles Define roles for your organization and choose their permissions. *** ## About This Task You can define custom roles and assign them to users. Custom roles let you control permissions at a granular level. You can create either create a role from scratch by choosing permissions for each asset, or start with a preset role and adjust its permissions. You can modify and delete roles any time. Keep in mind that changes to a role's permissions apply to all users and groups assigned to that role. # Prerequisites Learn about roles and permissions by reading [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). # Create a Role 1. In , click your profile icon and choose _Settings_. 2. Go to _Organization>Roles_. 2. Open **Custom Roles** and click **Create Custom Role**. 3. Give your role a name and, optionally, add a description to help identify it later. 4. Choose whether to: 1. Start by copying a preset role: 1. Choose the role. 2. Adjust the permissions as needed. 2. Start from scratch: Choose the permissions this role should have for each asset. 5. Click **Create Role**. The new role appears on the Roles page under Custom Roles in Organization Settings. # What To Do Next Assign your custom role to users and groups to control their access to workspaces. --- ## Enable Single Sign-On (SSO) Enable SSO for to let your users seamlessly log in. --- ## About This Task Single Sign-On (SSO) is a user authentication method for accessing multiple systems with one set of credentials. Users log in once and gain access to all connected systems without having to re-enter their credentials. supports SSO and SAML for integration with your identity provider. ## Enable SSO Reach out to your representative to enable SSO for . --- ## Generate API Keys API keys let you connect external applications to . You need them to use API endpoints or when working in an SDK. You can create API keys at the workspace or organization level with different roles and permissions. *** ## About This Task API keys authenticate your applications when making requests to the API. Each key has: - Scope: workspace or organization. Keys generated for a workspace grant access only to this specific workspace. Keys generated for an organization grant access to all workspaces in the organization. - Type: personal or service. Personal keys are tied to your user account. Service keys are for automated systems. They're not linked to a specific user. Instead of a username, the search history will show the key name as the actor. Use this type for production applications or systems that connect to . - Role: Determines what actions the key can perform. You can't grant the key more permissions than you already have. - Expiration: Optional expiration date for security. :::info API keys can't be used to create, modify, or delete other API tokens. This prevents unauthorized expansion of access. ::: ### Role Restrictions When creating an API key, you cannot grant the key more permissions than you already have: - Organization role: Only organization admins can create a token with the organization Admin role. If you are a member and request an Admin organization role for the token, the request fails with a `403` error. - Workspace role: The workspace role assigned to the token cannot exceed your own role in that workspace. For example, if you hold the Editor role in a workspace, you cannot create a token with the Admin role for that workspace. - Custom roles: Custom roles and default roles are incompatible. If you hold a custom role in a workspace, you can only create a token with that exact same custom role — not with any default role (External, Search User, Editor, or Admin), and not with a different custom role. Similarly, if you hold a default role, you cannot create a token with a custom role. Organization admins are exempt from workspace-level role checks and can create tokens with any role. ### Security and Best Practices - Use service keys for automated systems and production environments - Set expiration dates for keys used in temporary or testing scenarios - Regularly review and remove unused API keys - Store API keys securely and never commit them to version control - Use workspace-scoped keys when possible to limit access - Give your keys meaningful names so that you can easily identify them in the search history and audit logs ## Prerequisites Learn about available roles and their permissions to choose the right one for your key. Check [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). ## Generate an API Key from the UI ### For a Workspace 1. Click your profile icon in the top right corner and choose _Settings_. 2. Go to _Workspace>API Keys_. 3. Click **Create API Key**: 1. Choose if it's a personal or a service key. Tip: Choose the _Service_ type for production use cases and systems that connect to . 2. Give your key a name. This is optional, if you don't type any name, the key ID is used. It's recommended to give your keys a meaningful name so that you can easily identify them in the search history and audit logs. 3. Set the expiration date. 4. Choose the role to determine the key's permissions. 4. Click **Create API Key**. 5. **Important**: Copy and save your key. After you add it to , it remains masked. ### For an Organization 1. Click your profile icon in the top right corner and choose _Settings_. 2. Go to _Organization>API Keys_. 3. Click **Create API Key**: 1. Choose if it's a personal or a service key. Tip: Choose the _Service_ type for production use cases and systems that connect to . 2. Give your key a name. This is optional, if you don't type any name, the key ID is used. It's recommended to give your keys a meaningful name and description so that you can easily identify them in the search history and audit logs. 3. Set the expiration date. 4. Choose the workspaces this key can access. 5. Choose the role to determine the key's permissions. 4. Click **Create API Key**. 5. **Important**: Copy and save your key. After you add it to , it remains masked. --- ## Manage User Access Define and modify user permissions for workspaces in your organization. *** ## About This Task By default, organization members have no access to workspaces unless you give them the access. You must explicitly indicate the workspaces users can access and assign roles that define user permissions for a given workspace. You can change permissions and revoke user access to workspaces at any time. ## Prerequisites - Roles define permissions to assets within a workspace. The includes preset roles you can assign to members. If these preset roles don't meet your needs, create custom roles before assigning then. For details, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). - Make sure the user is already a member of your organization. If they're not, invite them. For details, see [Add Users to Organization](/docs/how-to-guides/managing-access/add-users-to-organization.mdx). ## Assign Roles and Grant Access to Workspaces 1. Click your profile icon in the top right corner, choose _Settings_. 2. Go to _Organization>Workspaces._ 3. Find the workspace you want to manage and click its name. 4. Go to **Manage Access**, select the member from the dropdown list, assign their role, and click **Save**. ## Revoke Workspace Access 1. Click your profile icon in the top right corner and choose _Settings_. 2. Go to _Organization>Workspaces. 3. Find the workspace you want to manage and click its name. 4. Go to **Manage Access**, find the user you want to remove, and click the delete icon next to their name. This removes the user from this workspace only. ## Remove Users from Organization 1. Click your profile icon in the top right corner and choose _Settings_. 2. Go to _Organization>Members_. 3. Find the user you want to remove from this organization and delete them. This removes the user from this organization and all its workspaces. --- ## Manage User Access(Managing-access) # Manage Users Add people to your organization, assign roles, manage workspace access, or delete users. *** --- ## Improving Your Document Search Pipeline There are multiple ways to improve your document search pipeline, such as changing the retrieval type, choosing a different model, adding a ranker, and many more. This guide explains each of them, helping you choose the one suitable for your use case. *** Document search pipelines are the first step of RAG pipelines. It's crucial to ensure they retrieve the correct documents, as these form the basis for the LLM's generated answers. ## Changing the Model `Embedders` are the pipeline components that turn strings (`TextEmbedders`) or documents (`DocumentEmbedders`) into embeddings. `TextEmbedders` are used before vector retrievers, such as `OpenSearchEmbeddingRetriever` in query pipelines, while `DocumentEmbedders` are used in indexes. If your pipeline uses a vector `Retriever` with an `Embedder`, you can first try to improve it by changing the `Embedder`'s model. Check the [models for retrieval](/docs/concepts/language-models-in-deepset-cloud.mdx) we recommend and try one. It's important to know that the `DocumentEmbedder` in your index and the `TextEmbedder` in your query pipeline must use the same model. ## Using the Hybrid Retrieval Approach ### With `HybridRetriever` You can use `OpenSearchHybridRetriever` to combine a vector and a keyword `Retriever`. It's the easiest way to achieve hubrid retrieval. Keyword retrievers can handle out-of-domain vocabulary and don’t need any training but can't capture semantic nuances. Semantic retrievers, on the other hand, can understand the context and semantics, but perform best in the domain they were trained on. Combining them allows you to take advantage of their strengths, improving your system's efficiency. `OpenSearchHybridRetriever` combines the two retrieval methods. It has a built-in text embedder, so you just need to connect it to `Input` and a Ranker or other component that consumes the retrieved documents. For details, see [OpenSearchHybridRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchHybridRetriever.mdx). ### With Two Retrievers You can manually combine a vector and a keyword `Retriever`. This is an example of a hybrid retrieval pipeline that uses the `OpenSearchBM25Retriever` and the `OpenSearchEmbeddingRetriever` and then merges the documents they fetch using the `DocumentJoiner` component. `DocumentJoiner` removes duplicates and leaves only unique documents. ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: "" max_chunk_bytes: 104857600 return_embedding: false settings: index.knn: true create_index: true top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 device: null embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: "" max_chunk_bytes: 104857600 return_embedding: false settings: index.knn: true create_index: true top_k: 20 # The number of results to return ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 20 device: null connections: - sender: bm25_retriever.documents receiver: ranker.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents ``` ## Adding a Ranker `Rankers` determine the relevance and order of documents in response to a query. Their primary goal is to present the most relevant documents at the top of the search results. While working with our customers, we found that rankers are better at determining the relevance of documents than retrievers. Adding a ranker can significantly improve the results. For ranking documents by relevance, we recommend using `CohereRanker` or `DeepsetNvidiaRanker`. Also, check the [ranking models](/docs/language-models-in-deepset#ranker-models) we recommend. Here's an example hybrid retrieval pipeline with a `TransformersSimilarityRanker`: ```yaml ## haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: Standard-Index-English max_chunk_bytes: 104857600 return_embedding: false settings: index.knn: true create_index: true top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 device: null embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: Standard-Index-English max_chunk_bytes: 104857600 return_embedding: false settings: index.knn: true create_index: true top_k: 20 # The number of results to return ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 20 device: null LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: bm25_retriever.documents receiver: ranker.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: LLM.documents inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - LLM.question filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents messages: LLM.messages ``` ## Prioritizing Documents Based on Their Metadata You can use metadata to customize how your documents are retrieved. For details, [Metadata for Ranking](https://docs.cloud.deepset.ai/docs/use-metadata-in-your-search-system#metadata-for-ranking). ## Finding the Optimal Preprocessing Configuration How your documents are preprocessed and prepared for querying influences the efficiency and accuracy of your app. `DocumentSplitter` is the component that chunks your files during indexing. You can modify its settings so that the resulting documents are clean, structured, and normalized to ensure efficient querying. Here are the `DocumentSplitter`'s settings you can modify to improve your app: - `split_by` - This specifies the unit by which you want to chunk your documents. Splitting by words is the safest option in most cases. You can consider splitting by `passage` if your documents have a clear paragraph structure, with each paragraph describing one idea. - `split_length` - This setting defines how big your documents can be at maximum. For example, if you choose to split your documents by words, `split_length` defines the maximum number of words your documents can have. This value can be bigger for keyword-based retrievers, but for vector-based retrievers, it must fit within the token limit of the retriever’s model. It’s best to check how many tokens the model was trained on and then set a value that fits within this limit. In our pipeline templates, we recommend setting this value to `250` words, which seems to work best in most cases. If your pipeline uses hybrid retrieval, you should adjust `split_length` to the token limit of the vector-based retriever model. --- ## Improving Your Question Answering Pipeline It can happen that the experiments fail or fall short of your expectations. It's nothing that can't be fixed. This page helps you figure out how to tweak your question answering pipeline to achieve the results you want. *** This page focuses on the extractive QA pipeline analysis here. If your pipeline didn't live up to your expectations, you could consider optimizing `PreProcessors`, `Retriever`, or `Reader`. ## Optimizing the Splitter Splitters, like `DocumentSplitter`, split your documents into smaller ones. To improve its performance, you can change the value of the `split_length` parameter. It's best to set this parameter to a value between 200 and 500 words. This is because there is a limit on the number of words an embedding retriever can process. The exact number depends on the model you use for your retriever, but once the document length passes that number, it cuts off the rest of the document. ## Optimizing the Retriever When evaluating the `Retriever`, it's good to start with `OpenSearchBM25Retriever`, as it's the standard. Here's what you can try: - Increase the number of documents the retriever returns. Use the `top_k` parameter to do that. This will increase the chances that the retriever sees a document containing the right answer. Doing this, though, slows down the search system as the reader must then check more documents. - Replace the `OpenSearchBM25Retriever` with `OpenSearchEmbeddingRetriever`. Have a look at the [Models for Information Retrieval](/docs/concepts/language-models-in-deepset-cloud.mdx) and check if any of them outperforms the BM25 retriever. - Send the combined output of both `BM25Retriever` and `EmbeddingRetriever` to the next component consuming the documents. For tips on how to improve the retrieval part of your pipeline, see [Improving Your Document Search Pipeline](/docs/how-to-guides/optimizing-your-pipeline/improving-your-document-retrieval-pipeline.mdx). ## Optimizing the Reader ### Finding the Right Model Metrics are an important indicator of your pipeline's performance, but you should also look into the predictions and let other users test your pipeline to get a better understanding of its weaknesses. To get an idea of what metric values you can achieve, check the metrics for state-of-the-art models on Hugging Face. Make sure you're checking the models trained on question answering datasets. Ideally, you should find a dataset that closely mirrors the one you're evaluating in . For example, to find models trained on a particular dataset in [Hugging Face](https://huggingface.co/), go to _Datasets>Tasks_ and choose _question-answering_ under the _Natural Language Processing_ category. When you click a particular dataset, you can see its details and all the models trained on it. You can then check the model cards for performance benchmarks. Try different reader models. For more guidance, see [Models for Question Answering](/docs/language-models-in-deepset#reader-models-for-question-answering). When choosing a model, remember that larger models usually perform better but are slower than smaller ones. You must decide on a balance between reader accuracy and search latency that you're comfortable with. ### Fine-Tuning the Reader Model If you find that none of the available models perform well enough, you can always fine-tune a model. To do that, you need to collect and annotate data. Our experience is that collecting feedback in doesn't boost the reader performance as much as annotated data. Once you have all the data, fine-tune the best-performing reader models you tried in the previous steps with the data you collected. ### Reducing Duplicate Answers If your search returns duplicate answers coming from overlapping documents, try reducing the `split_overlap` value of `DocumentSplitter` to a value around or below 10. --- ## Boosting Retrieval with OpenSearch Queries uses OpenSearch through `OpenSearchDocumentStore` to store documents. At query time, the `Retriever` connects to OpenSearch to fetch the documents that are most relevant to the query. You can pass a custom query to the `Retriever` to fetch the documents based on this query. *** :::tip Recommended Reading Before you dig into this topic, it's good to understand how the `Retriever` works. Have a look at `Retrievers` to learn more. We also recommend you get a general understanding of the OpenSearch query syntax. ::: :::info `OpenSearchDocumentStore` This guide is for users of the `OpenSearchDocumentStore`, the core document store uses. If you're using a different document store, like Qdrant, Pinecone, or Weaviate, you won't be able to use the techniques described here. ::: You can pass a custom OpenSearch query to `OpenSearchBM25Retriever` and `OpenSearchEmbeddingRetriever` to specify how you want to fetch `Documents` from `OpenSearchDocumentStore`. With a custom query, you can prioritize documents based on their characteristics, such as a metadata field value, the date a document was created, and so on. This page covers the most common cases when you may want to write custom OpenSearch queries. ## Prioritizing the Most Recent Documents You can use the Gaussian decay function to prioritize the most recent documents. This function penalizes marginal time deltas. ### Example Query This query matches documents based on the `$query` string against the `content` field and any submitted filters. It then decreases the relevance score of the documents as they get older. The query favors documents newer than 30 days. ```json { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "gauss": { "file_created_at": { "origin": "now", "offset": "30d", "scale": "730d" } } } } } ``` The first part defines `function_score` as `query`. This query type changes the relevance score the Retriever assigns to Documents using the function you specify in your custom query. Within the `function_score`, we further specify the query to match the `$query` value against the `content` field in your documents. If `$query` contains multiple words, the `match` query returns all documents that contain any of the words from the `$query`. This means that if the query is "Joe Biden", the query returns documents containing "Joe", "Biden", or both. `$filters` allows us to use filters as usual. Queries prioritizing the most recent documents often use the Gaussian decay function, which penalizes marginal time deltas. This is the case in this query as well. `gauss` refers to the Gaussian function the query applies to your documents based on the `file_created_at` field. This means the score of each document decreases (or decays) the further the value in its `file_created_at` field is from the `origin` value. #### Parameters The `origin` parameter defines the point where the decay starts. Setting it to `now` means the decay starts from the current time. The `offset` parameter is the distance from the origin at which the decay starts. Up until the value defined in `offset`, the relevance score of your documents is not affected. This query sets the offset to 30 days, which means documents created within the last 30 days won't have their score affected by the Gaussian function. The `scale` parameter defines the rate of decay. Here, it's set to 730 days (about 2 years), which means the score of the document is decreased by half when the value in its `file_created_at` field is 730 days away from the value set in `origin`. #### Used in a Pipeline When using an OpenSearch query in a YAML pipeline, pass it in the `Retriever`'s `custom_query` parameter and then connect the `Retriever` to other components, like you normally would: ```yaml components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - "${OPENSEARCH_USER}" http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 768 similarity: cosine top_k: 20 custom_query: { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "gauss": { "file_created_at": { "origin": "now", "offset": "30d", "scale": "730d" } } } } } ``` ### Other Options If the Gaussian decay function doesn't match your use case, you can also use the following functions: - `exp` for exponential decay. - `linear` for linear decay. For more information about functions and their parameters, see [OpenSearch documentation](https://opensearch.org/docs/latest/query-dsl/query-dsl/compound/function-score/#decay-functions). ## Prioritizing Documents Based on Metadata Field Values You can favor documents with a specific value in a given metadata field. This can be a textual value or a numerical value. ### Prioritizing Based on Textual Values This method is useful if you want to prioritize documents with metadata fields containing a text string. For example, you can give the highest priority to documents with the metadata field `file_type="article"` and slightly lower priority to documents with metadata field `file_type="paper"` and the lowest priority to documents with metadata field `file_type="comment"`. You do this by assigning `weight` to each metadata field value. Note that filters won't work with this query. #### Example Query ```json { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "functions": [ { "filter": { "terms": { "file_type": ["article", "paper"] } }, "weight": 2.0 }, { "filter": { "terms": { "file_type": ["comment"] } }, "weight": 1.5 }, { "filter": { "terms": { "file_type": ["archive"] } }, "weight": 0.5 } ] } } } ``` As in the query above, it starts with the `function_score`, which means we want to change the relevance scores of the documents. Within `function_score`, we tell the query to match the `$query` value against the `content` field in your documents. Filters will also be applied as usual thanks to `$filters`. The next part of the query contains the functions to be used. Within the functions, the query is defined to filter for particular metadata field values and assign weight to them. The higher the weight, the higher the priority of the metadata field value. In this particular query, documents with `file_type="article"` or `file_type="paper"` metadata fields have the highest priority with their BM25 score doubled. Then, we tell the query to boost the relevance score of documents with the `file_type="comment"` metadata field by 1.5 times, which is less than articles and papers but still higher than other document types. And finally, we penalize documents with `file_type="archive"` metadata field by decreasing their relevance score by half. #### Parameters - `filter` - The filter to apply. Use the `terms` filter for categorical data. - `weight` - The value by which the BM25 score of the documents matching the filter criteria will be multiplied. #### Used in a Pipeline To use the custom query in a pipeline, pass the query in the `custom_query` parameter of the retriever and the connect the retriever to other components, like you normally would: ```yaml components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - "${OPENSEARCH_USER}" http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 768 similarity: cosine top_k: 20 custom_query: { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "functions": [ { "filter": { "terms": { "file_type": ["article", "paper"] } }, "weight": 2.0 }, { "filter": { "terms": { "file_type": ["comment"] } }, "weight": 1.5 }, { "filter": { "terms": { "file_type": ["archive"] } }, "weight": 0.5 } ] } } } ``` ### Prioritizing Based on Numerical Values You can construct a query to prioritize documents with a metadata field containing numerical values. Say you collect popularity metrics for your documents, such as likes, and you want to favor documents that are the most popular. #### Example Query Let's look at a query that prioritizes documents with the most likes. Note that filters won't work with this query. ```json { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "field_value_factor": { "field": "likes_last_month", "factor": 0.1, "modifier": "log1p", "missing": 0 } } } } ``` As previously, first we tell the query to score documents based on how well they match the provided `$query` in the `content` field. Filters will also be applied as usual thanks to `$filters`. It uses the `field_value_factor` function to adjust the scores of the documents based on the metadata field `likes_last_month`. `factor` multiplies the value of the field by `0.1` before the `modifier` function is applied. You can think of the `factor` parameter like a spotlight. Setting it to a smaller value, like `0.1`, focuses the spotlight on the most relevant documents. Together with the `log1p` modifier, it's like saying that the number of likes is most meaningful at the values around 100. This kind of tweaking comes in handy because different fields can have different ranges of values. For example, the `likes_last_month` field might have values ranging from 0 to several thousand. By setting the factor to `0.1`, we make sure that when we reach the value of `100` likes, it's like we're multiplying the original text matching score by roughly `1.0`. If the likes are under `100`, the text matching score is decreased. If the likes are above `100`, the text matching score is increased according to the `modifier` function. `modifier` defines how we want to modify the value of the metadata field after it's multiplied by `factor`. Here the modifier is the `log1p` mathematical function which adds 1 to the value of the `likes_last_month` field to avoid negative values and then takes the logarithm of base 10. This helps prevent documents with exceptionally high numbers of likes from dominating the rest of the documents to balance out the impact of likes on the overall score of the document. Finally, if a document doesn't have the `likes_last_month` metadata field, we want to assign the ranking score of `0` to it, hence `"missing":0"`. #### Parameters - `field` - the name of the metadata field whose value you want to use for calculating the relevance score of the document. - `factor` - the number by which the value of the metadata field will be multiplied before the `modifier` is applied to the value. - `modifier` - the function you want to use to modify the field value. - `missing` - the value you want to use for the document if the field is missing from it. For more details, see the[ OpenSearch Field Value Factor function documentation](https://opensearch.org/docs/latest/query-dsl/query-dsl/compound/function-score/#the-field-value-factor-function). #### Used in a Pipeline ```yaml components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - "${OPENSEARCH_USER}" http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 768 similarity: cosine top_k: 20 custom_query: { "query": { "function_score": { "query": { "bool": { "must": { "match": { "content": $query } }, "filter": $filters } }, "field_value_factor": { "field": "likes_last_month", "factor": 0.1, "modifier": "log1p", "missing": 0 } } } } ``` #### Other Options You can use other functions as the `modifier`. For a full list, see [OpenSearch documentation](https://opensearch.org/docs/latest/query-dsl/query-dsl/compound/function-score/#the-field-value-factor-function). ## Enabling Fuzzy Matching You can use OpenSearch queries to account for small spelling errors users may make when typing the query. #### Example Query ```json { "query": { "bool": { "must": { "multi_match": { "query": $query, "fields": ["content"], "fuzziness": "AUTO", "operator": "or" } }, "filter": $filters } } } ``` You can experiment with the `fuzziness` parameter. `AUTO` sets it to a value that makes sense in a given context. You can choose a small integer to set the specific number of corrections allowed. For example, to handle the query: "waht is political correctness", you need `fuzziness: 3` as you need three modifications to bring this level to the originally intended meaning. In our experiments, setting `fuzziness: "AUTO"` handled cases with three corrections well. You may think about setting this parameter manually if you find that `AUTO` is too allowing or too strict for your use case. Enabling fuzzy matching can potentially lower the pipeline's recall, so it's always important to run experiments before moving your pipeline to production. To avoid drastic recall loss, make sure you set the `operator` to `OR`. It allows returning matches even if not all words from the query are present. That's very useful, as when asking questions, you use a lot of auxiliary words to formulate the query, but they don't need to be present in the document. For example, if you ask, "How can I do X in Y app?", "How can I" are auxiliary words, and you only care about "X in Y app." With the `AND` operator, the document will only be returned if it has all the words from the query. #### Used in a Pipeline Pass it as a multi-line string in the `custom_query` parameter or the retriever: ```yaml components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - "${OPENSEARCH_USER}" http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 768 similarity: cosine top_k: 20 custom_query: { "query": { "bool": { "must": { "multi_match": { "query": $query, "fields": ["content"], "fuzziness": "AUTO", "operator": "or" } }, "filter": $filters } } } ``` --- ## Debug with Logs Logs are enabled for every pipeline and index by default. *** ## Viewing Pipeline Logs 1. In , go to **Pipelines** and click the name of the pipeline you want to debug. 2. Switch to **Analytics** and open the **Logs** tab. ## Viewing Index Logs 1. In , go to **Indexes** and click the name of the index you want to debug. 2. Switch to **Logs**. 1. To view pipeline logs, choose **Pipelines**. 2. To view index logs, choose **Indexes**. 2. Click the name of your pipeline or index to open its details. 3. Open the **Logs** tab. You can filter the logs by message and pipeline type or date added. You can also search for keywords in log messages. To download the logs, click **Download CSV**. :::tip Other Log sources After you run a pipeline in Builder, you can see its real-time logs right there. You can also see real-time logs for a particular request in Playground. For details, see [Test Your Pipeline in Playground](../searching-with-your-pipeline/run-a-search.mdx). To debug while building, use the logs in Builder. To learn how to do it, see [Debug with Pipeline Builder](./debug-with-pipeline-builder.mdx). ::: --- ## Debug with Pipeline Builder # Debug with Builder Fix your pipeline issues. Submit a query and examine the detailed component logs to understand how the component processed it to produce the final result. *** ## About This Task You can debug your pipeline by checking the component logs for each run. You can also use the Issues panel to see all validation and runtime issues in one place. Click **Inspect** next to any issue to jump directly to the affected component or connection and fix it. Click **Fix with AI** next to any issue to open the AI assistant, which reasons through the fix and can apply it for you. ## Check Component Logs You can inspect each component's logs per run to understand how the component processed the input and produced the output. 1. Open your pipeline in Builder. 3. Click **Run Pipeline** above the `Input` component and type a query in the Playground window that pops up. 4. Wait until you get an answer and minimize the Playground window using the down arrow. 5. Check the components in your pipeline. There is a _Logs_ tag on the components whose logs you can view. Click **View** on a component to see its output logs. :::tip Check the Issues Panel After running the pipeline, you can also open the **Issues** tab at the bottom of Builder to see all runtime errors in one place. Click **Inspect** next to any issue to jump directly to the affected component. Click **Fix with AI** to open the AI assistant, which reasons through the fix and can apply it for you. ::: :::info Component Logs Component logs are automatically available for all components in your pipeline when debugging. This includes intermediate processing steps and outputs from each component, helping you trace how data flows through your pipeline. ::: ## Use the AI Assistant Builder includes a built-in AI assistant you can chat with to get help debugging your pipeline. Click **AI Assistant** in Builder to open the chat panel. Describe what's going wrong, paste an error message, or ask the assistant to help you understand unexpected behavior. The assistant was designed with debugging in mind, but you can use it for other things too — like getting help with pipeline design or understanding how a component works. The AI assistant runs as a streaming chat, so responses appear as they are generated. Each session keeps context across turns, so you can follow up on previous questions without repeating yourself. ## Debug Single Components Run individual components to verify their settings, input and output, and check if they work as expected. For information on how it works, see [Run Components in Isolation](/docs/how-to-guides/designing-your-pipeline/run-components-in-isolation.mdx). --- ## Debug Your Query Pipelines Remotely Debug your pipelines using a Visual Studio Code (VSCode) remote tunnel. *** ## About This Task Inspect, monitor, and debug your query pipelines running in the target environment—securely and without complex VPN or SSH setups. This method uses VS Code tunnels with GitHub authentication, accessible through a web browser, so you don’t need to install VS Code locally. For details on how the tunneling feature works, see [VS Code documentation](https://code.visualstudio.com/docs/remote/tunnels#:~:text=The%20Visual%20Studio%20Code%20Remote,without%20the%20requirement%20of%20SSH.). When you choose to debug your pipeline in VSCode, shows you a notification with a link and an eight-character code to authenticate in GitHub and a link to browser-based VSCode. The notification stays visible until you close it. :::info Setting up the tunnel may take a couple of minutes. If you open the link before the tunnel is ready, you'll see an error message saying the tunnel wasn't found. If this happens, reload the page after around 30 seconds. ::: After you authenticate in GitHub and you open VSCode, you can see a couple of files in the _Debug_ folder in VSCode's Explorer: - `pieline.yaml`: This is the configuration of the pipeline you want to debug. - `debug_custom_component.py` and `debug_pipeline.py`: These are sample files to show you how to debug custom components and pipelines, respectively. - `utlis.py`: This is a sample file to show you how to set up your environment for debugging. The debug tunnel stays open for 12 hours. After that time, it's automatically closed. :::info Debugging in Playground You can also debug your pipeline when testing it in Playground. Just click the debug icon and you'll be able to track all the steps your pipeline performs in real time. For details, see [Test Your Pipeline in Playground](../searching-with-your-pipeline/run-a-search.mdx). ::: ## Prerequisites - A deployed and active pipeline to debug. - A GitHub account. - Advanced knowledge of VSCode and remote debugging. - Good knowledge of Python. ## Debug Your Pipeline 1. In , go to **Pipelines**. 2. Locate the pipeline you want to debug, click the More Actions menu next to it, and choose _Debug in VS Code_. 3. When you see a notification at the top of the screen, click the GitHub link. 4. When you're redirected to GitHub: 1. Log in to your GitHub account. 2. When prompted, enter the code from the notification. 3. Authorize Visual Studio Code. 5. When VSCode is successfully authorized, go back to and open the VSCode link in the notification. This takes you to a browser-based VSCode instance. You may need to authenticate the necessary VSCode extensions in GitHub. You can find your pipeline in the `pipeline.yaml` file. Use the sample Python files to understand how to debug it. :::tip If the Python tools didn't load or you're getting a message the tunnel wasn't found, reload the page. ::: --- ## Use Your Pipeline in Your Target App Add the search functionality to your app and configure how your search results are displayed. The `search` API endpoint is all you need. *** ## About This Task We recommend setting the pipeline you plan to use in your app to the Production service level. This ensures the pipeline's scalability and reliability in production use cases. For more information, see [Pipeline Service Levels](/docs/about-pipelines#pipeline-service-levels). ## Use the Search Endpoint in Your App First, [generate an API key](/docs/how-to-guides/managing-access/generate-api-key.mdx) and save it. The easiest way is to start with the API Reference documentation: 1. Go to the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) endpoint documentation page. 2. Enter the necessary parameters: - In the *Bearer* field, paste the API key you previously generated. - Type the name of the pipeline to use for the search. - Type the workspace name containing the pipeline you want to use in your target app. - Optionally, add filters. (You can use metadata from your documents as filters to narrow the search. For more information, see [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx).) - Optionally, add any runtime parameters for the pipeline components. - Type the queries. 3. Choose the programming language that you want to use and copy the code. You can then wrap this code in a function and modify it as needed. ## Set Default Pipeline Consider [setting the default pipeline](/docs/how-to-guides/searching-with-your-pipeline/set-default-pipeline.mdx) for your app. Use the [Set Default Pipeline](/docs/api/main/set-default-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-default-post.api.mdx) API endpoint to route all traffic to the pipeline you indicated as default. This way, when you need to tweak or change your pipeline, you can do so without any downtime. Just indicate the new default pipeline, and all traffic will be seamlessly routed to this pipeline without your users ever noticing. ## Format Your Search Results For question answering pipelines, you can highlight the answer in the document, which makes it much easier for the users to spot it. Here is an example of what it looks like: The response for a question answering pipeline contains the exact position of the answer both in the document (`offsets_in_document`) and in the context (`offsets_in_context`). You can use it to format how the answers are displayed. ## Integrate with Your Frontend App See [Tutorial: Integrating API with Your Frontend App](/docs/tutorials/learn-the-basics/tutorial-connecting-to-ui.mdx) to learn how to integrate API with your UI. ## Idle Pipelines Unused pipelines become idle after a period of inactivity to save resources. By default, development pipelines become idle after 20 minutes and production pipelines after 24 hours. You can customize the idle timeout on the Pipeline Detail page, in the *Settings* tab. Idle pipelines get automatically activated if you start searching with them, or you can activate them manually on the Pipelines page. When a pipeline is idle, your data remains perfectly safe and accessible anytime. For more information, see [Pipeline Service Levels](/docs/concepts/about-pipelines/about-pipelines.mdx#pipeline-service-levels). --- ## Use Your Pipelines as MCP Tools Create a workspace MCP server and expose your deployed pipelines as tools that AI assistants, like Claude Code or Cursor, can call directly. *** ## About This Task MCP (Model Context Protocol) standardizes how AI applications communicate with external tools and services. In , you set up one MCP server for your workspace and choose which deployed pipelines to expose as tools. A new MCP server has no tools by default. You enable each pipeline individually in its settings. Once enabled, your AI assistant can call any of those pipelines and use the results. For example, you can add a RAG pipeline as a tool to let your AI assistant query your internal knowledge base, or add a data processing pipeline to transform content in your development workflow. You can brand your server with a name, description, icon, and instructions to control how your AI assistant sees and uses it. To learn more about MCP, see [Model Context Protocol](/docs/concepts/model-context-protocol.mdx). ## Prerequisites - One or more deployed pipelines in your workspace. - The `pipelines:write` permission for the workspace. - The `MCP Server` permission for the workspace. Admin and Editor roles have read and write access by default. Search User role has read-only access by default. Users on custom roles won't see MCP features until an admin grants the `MCP Server` permission to that role. For details on permissions, see [User Roles and Permissions](/docs/concepts/user-roles-and-permissions.mdx). - A basic understanding of the Model Context Protocol (MCP). ## Create an MCP Server To use your pipelines as MCP tools, perform these steps: 1. Create an MCP server for your workspace. 2. Enable individual pipelines as tools. ### 1. Create a Workspace MCP Server You create one MCP server per workspace. Creating the server does not automatically expose any pipelines — you enable each pipeline as a tool separately in the pipeline's own settings. 1. In , click your profile icon and go to *Settings > Workspace > MCP*. 2. Click **Create MCP Server**. 3. Type a name for the MCP server. 4. Optionally, provide the following information: - The server version. This is the version of the MCP protocol. Your AI assistant sends the version number in the initial call to the server. You can leave this field blank to use the latest version. - Website URL. This is the URL of the company that built the MCP server. You can provide your company's URL here or leave it blank. - Icon URL. This is the URL of the custom icon for the MCP server. Use SVG or PNG format. Note that currently not all AI assistants can display custom icons. - Instructions. Provide guidance to the AI assistant on how to use your pipeline tools effectively. The text you enter as instructions is injected into the AI assistant's prompt at the start of every session, so it applies globally to all pipeline tools. Give instructions beyond what the pipeline tool description provides, such as the order for calling pipelines, dependencies between them, or known limitations. The workspace MCP server is now ready. You can see pipelines available as MCP tools for this workspace. Next, enable individual pipelines as tools. ### 2. Enable Pipelines as Tools :::info Deployed Pipelines A pipeline must be deployed to be used as an MCP tool. The MCP tool toggle is only enabled when the pipeline is deployed or on standby. ::: Pipelines are not added to the MCP server automatically. You enable each one explicitly in its settings. You can do it in two ways, either from the Workspace Settings page or from the Pipeline Details page. #### From the Workspace Settings page Create a workspace MCP server first. Follow the steps in [Create a Workspace MCP Server](#1-create-a-workspace-mcp-server). Once the MCP server is created for the workspace: 1. On the Workspace Settings > MCP page, scroll down to MCP Tools. You can view all pipelines you can enable as MCP tools here. 2. Click a pipeline you want to enable as a tool. You're redirected to the Builder. 3. Switch to the **Settings** tab. 4. In the MCP Tool section, turn on **Use as MCP tool**. 5. Choose the pipeline version to use the tool. If you leave it empty, it uses the deployed version. 6. Optionally, provide a custom tool name or leave the pipeline name as is. Names help the AI assistant choose the right tools. Make sure the name is unique and descriptive. 7. Optionally, provide a custom tool description or leave it empty to autogenerate one. Descriptions tell the AI assistant when and how to use the tool. 8. If you have an API key for the workspace, paste it into the field. If you don't have one, click **Create** to generate it. The key is automatically named after the pipeline with the *MCP* prefix, for example, *MCP — my-pipeline*. You can find it later in your workspace settings under API Keys. Return to the Workspace Settings page and repeat these steps for each pipeline you want to expose. All enabled pipelines share the same workspace MCP endpoint and API key. :::info Pipeline Configuration Issues The MCP Tools list may show a warning icon next to a pipeline if that pipeline is not currently deployed or is on standby. This can happen when a pipeline has configuration errors that prevent it from running. Open the pipeline's settings to review and fix any issues before using it as a tool. ::: #### From Pipeline Settings :::info Enabling a Pipeline as an MCP Tool Without a Workspace MCP Server You can enable a deployed pipeline as an MCP tool without creating a workspace MCP server. When you expose a pipeline as a tool, the workspace MCP server is created automatically behind the scenes. ::: 1. Go to **Pipelines** and click the pipeline you want to enable as a tool. 2. Click **Settings**. 3. In the MCP Tool section, turn on **Use as MCP tool**. 4. Choose the pipeline version to use the tool. If you leave it empty, it uses the deployed version. 5. Optionally, provide a custom tool name or leave the pipeline name as is. Names help the AI assistant choose the right tools. Make sure the name is unique and descriptive. 6. Optionally, provide a custom tool description or leave it empty to autogenerate one. Descriptions tell the AI assistant when and how to use the tool. 7. If you have an API key for the workspace, paste it into the field. If you don't have one, click **Create** to generate it. The key is automatically named after the pipeline with the *MCP* prefix, for example, *MCP — my-pipeline*. You can find it later in your workspace settings under API Keys. ## Connect Your AI Client You can find ready-to-use configuration snippets in the MCP server settings. 1. Open a pipeline and switch to **Settings**. 2. Go to *MCP Tool>Client Config* section. 3. Choose your client format: - **Cursor / VS Code**: JSON configuration for `mcpServers` - **Claude Code**: CLI command for adding the server - **Raw URL**: Direct MCP endpoint URL 4. Click **Copy** to copy the configuration. 5. Paste it into your AI client according to its setup instructions. When the AI client connects, it receives the list of all tools (pipelines) available on the server and can call them as needed. ### Example Configurations #### Cursor / VS Code (JSON) ```json { "mcpServers": { "haystack-enterprise": { "url": "https://api.cloud.deepset.ai/api/v2/workspaces//mcp", "headers": { "Authorization": "Bearer your-api-key" } } } } ``` #### Claude Code (CLI) ```bash claude mcp add-json haystack-enterprise '{ "type": "http", "url": "https://api.cloud.deepset.ai/api/v2/workspaces/your-workspace-id/mcp", "headers": { "Authorization": "Bearer your-api-key" } }' ``` ## Disable a Pipeline Tool or Delete the MCP Server ### Disable a Pipeline Tool To stop use a specific pipeline as a tool without affecting the rest of the server: 1. Go to **Pipelines** and click the pipeline you want to remove. 2. Click **Settings**. 3. In the **MCP Tool** section, turn off **Use as MCP tool**. The pipeline is immediately removed from the server. Other enabled pipelines continue to work. ### Delete the MCP Server To stop using your workspace as an MCP server entirely: 1. Go to **Settings > Workspace > MCP**. 2. Switch off **Create MCP Server**. The server and all its tools are immediately removed and can no longer be used by external clients. ## Troubleshooting - **The MCP section is grayed out**: You need the `pipelines:write` permission for the workspace. Contact your workspace administrator to assign the appropriate role. - **The MCP tool toggle is disabled**: The toggle can be disabled for several reasons. Hover over the toggle to see the reason. Common causes are: the pipeline is not deployed (deploy the pipeline first), you don't have write access to the MCP server (contact your workspace administrator), or the pipeline has no published versions. - **A warning icon appears next to a pipeline in the MCP Tools list**: The pipeline is not in a deployed or standby state and cannot currently serve as an MCP tool. Click the pipeline to open its settings, check for configuration errors, and redeploy it. - **AI client can't connect**: Verify your API key is correct and has the necessary permissions. Try copying the configuration snippet again from the server settings. - **Changes aren't saving**: Settings are saved automatically with a short delay. Wait a few seconds after making changes before navigating away. ## Related Information - [Model Context Protocol](/docs/concepts/model-context-protocol.mdx) - [Generate API Keys](/docs/how-to-guides/managing-access/generate-api-key.mdx) - [Model Context Protocol Official Website](https://modelcontextprotocol.io/) - [Writing MCP Server Instructions](https://blog.modelcontextprotocol.io/posts/2025-11-03-using-server-instructions/) --- ## Implement CI/CD with Github Actions Use our customizable template to manage deployments across development and production workspaces, following best practices for automation. *** We provide a GitHub repository containing a fully functional CI/CD template with GitHub Actions. Check the repository at [GitHub](https://github.com/deepset-ai/deepset-cloud-github-action-template). --- ## Monitor Pipeline Performance If you're wondering how many requests you can send from your search system to or what speed you can expect, here are your answers. Use built-in metrics, logs, and KPI dashboards to monitor your pipeline performance. *** ## Scaling Unexpected surges in traffic are a challenge, but seamlessly handles scalability in response to increased demand. uses autoscaling, which automatically adjusts the infrastructure based on the usage. This ensures there are no disruptions in service, regardless of the number of concurrent requests. The system dynamically reallocates resources to maintain optimal performance. Scaling is entirely automated and doesn't require any manual adjustments from you. ## Speed Several factors influence the speed of your search system: - Model size Pipelines with large models are slower. With LLMs, it's often a tradeoff between speed and performance. Large models, like GPT-5, may give better answers than smaller models, but they're also much slower because of their size. - Where your model runs You can run models locally, on your machine, or remotely, through API. Small models used with Retrievers or Readers are faster to run locally because they don't need much power. Large models, like ChatGPT or GPT-4, need dedicated and optimized hardware, and running them remotely is usually faster. - Pipeline configuration Some components or their settings can slow your pipeline. For example, a Ranker improves the results but also slows the system down. The same goes for a Reader with a high `top_k` value. It's often about finding the balance between speed and performance. - The length of generated responses For generative QA pipelines, the number of tokens you want the model to generate as an answer influences your system's speed. The longer the answer, the slower the system. Optimizing the speed of your pipeline is all about finding the balance among these factors. It involves choosing the right-sized model, running it where it's fastest, and finding a configuration with optimal performance. If your pipeline contains components that work better on a GPU, turn on GPU acceleration. For details, see [Enable GPU Acceleration for Pipelines](/docs/how-to-guides/designing-your-pipeline/set-additional-params/enable-gpu.mdx). ## Pipeline Analytics To check what queries were asked, the top answers, and how long it took to find them, click the pipeline's name on the Pipelines page and switch to *Analytics*. This brings you to the pipeline overview, where you can view all the information about your pipeline. ### Overview The Pipeline Overview shows a KPI dashboard with key performance metrics in an easy-to-read format: - Total queries: Total number of queries your pipeline processed. This metric helps you understand usage patterns and traffic volume. - Documents: Total number of documents indexed for this pipeline. - Feedback coverage: Percentage of queries that received user feedback. Higher feedback coverage gives you better insights into pipeline performance. If this shows "N/A", it means no feedback was given yet. - Average response time: Average time it took to generate a response. Monitor this metric to identify performance issues or improvements after configuration changes. - Minimum inference time: The fastest response time recorded across all queries. This helps you understand your pipeline's best case performance. - Maximum inference time: The slowest response time recorded across all queries. Use this metric to identify potential performance bottlenecks or outliers. - Query volume: Number of queries your pipeline processed over the last 7 days. - Feedback distribution: Distribution of feedback received for the pipeline's responses. You can click on any slice of the pie chart to navigate to the Search History tab with the feedback rating filter automatically applied for that feedback category (Accurate, Inaccurate, or Wrong Document). This lets you quickly drill down into specific feedback types for detailed analysis. - Query Activity Heatmap: Shows when your pipeline is most active by displaying query volume across hours and days. This helps you understand usage patterns, identify peak activity period, or plan maintenance windows. ### History For detailed performance and feedback analysis, use the History tab to review individual queries and responses. You can generate executive summaries with AI-powered Feedback Insights. You can start with one of the suggested prompts or enter your own query. Based on the prompt, AI analyzes your pipeline activity and generates a summary. Customize the table to show the columns you need, and view the conversation history for each query. You can choose the pipeline version whose history you want to view. Use notes and hashtags to add context to your queries and responses. Both notes and hashtags are searchable. You can view and manage them if you enable the Notes and Hashtags columns in the Search History table. To do this: 1. Click **Manage table preferences**. 2. Choose to display the *Note* and *Hashtags* columns. You can then add notes and hashtags to your queries using these columns in the table. You can now see notes and hashtags for each query in the History table. You can also view and manage them in the detailed view for each query. Use this information to identify slow queries, improve answer quality, and understand user needs. Download the search history as a CSV file for further analysis. The exported CSV file includes the following columns: - `query_id`: The unique identifier for each search history record. Use this column to reference a specific query in your integration or downstream tooling. - `answer`: The answer text returned for the query. For retrieval and agent pipelines, this is populated from the first retrieved document's content when no explicit answer is present. - `file_name`: The name of the source file associated with the result. For retrieval and agent pipelines, this falls back to the file from the first retrieved document. - `file_id`: The unique identifier of the source file. Resolved the same way as `file_name`. - `created_at`: The timestamp of when the query was made, in ISO 8601 format. If your integration uses the legacy column name `time`, it continues to work and returns the same value. - `feedback_created_at`: The timestamp of when user feedback was submitted for the query, in ISO 8601 format. This column is empty when no feedback has been given for a query. - `pipeline_version_id`: The ID of the pipeline version that served the query. This lets you tie each query row to the exact pipeline version that served it, which is useful when you have multiple versions deployed and want to compare behavior or investigate a specific version. When you navigate to Search History from the Feedback Distribution chart, the feedback rating filter is automatically applied to show only queries matching the selected feedback type. You can clear this filter or add additional filters as needed. ## Logs Check pipeline logs to see what happened since it was deployed. You can view the logs on the Pipeline Details page (just click the pipeline name to get there). Expand messages for more details and possible actions. ## Traces supports tracing with Langfuse and Weights & Biases' Weave. To learn how to set up tracing, see [Trace Your Pipelines](./trace-your-pipelines.mdx). ## Related Information - [Understand Your Pipeline Usage](./understand-pipeline-usage.mdx) - [Trace Your Pipelines](./trace-your-pipelines.mdx) --- ## Productionizing Your Pipeline Implementing a robust search system requires strategic productionization for scalability and performance. Understanding the critical steps and best practices makes the transition from a prototype to a production-ready solution smooth and efficient. *** ## Choose Your Pipeline An effective pipeline is the foundation of your search system. It’s crucial to test and evaluate it thoroughly to ensure its performance meets the users’ needs. Have a look at this checklist and make sure you completed each of these tasks: - [ ] [Collect feedback](/docs/how-to-guides/evaluating-your-pipeline/collect-feedback.mdx) on the chosen pipeline from a small group of test users. - [ ] Compare a few different pipelines and discern the best one. - [ ] For generative pipelines using an LLM, optimize your prompt. You can use [Prompt Explorer to help you test](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx). If you find that your pipeline still needs improvements, see the *Optimizing Your Pipeline* section. ## Plan Your App The success of your search system hinges not only on the quality of your pipeline but also on the usability of your user-facing app. When planning your app, consider the points below. ### Your Data If your pipeline operates on static data, you just need to [upload your files](/docs/how-to-guides/working-with-your-data/upload-files.mdx) to or your VPC, and you’re set. If your data changes frequently, set up a continuous data integration. Make sure you enable overwriting of outdated files. See [Uploading Asynchronously](/docs/how-to-guides/working-with-your-data/upload-files.mdx) for example scripts and the [tutorial](/docs/tutorials/learn-more-advanced-features/tutorial-uploading-files-with-python-methods.mdx) for end-to-end instructions. You can also use Airbyte to set up regular syncs between your data source and . For details, see [Synchronize Data Using Airbyte](/docs/how-to-guides/working-with-your-data/synchronize-data-using-airbyte.mdx). ### Scaling takes care of the scaling for you, so you don't need to worry about it. For capabilities and benchmarks, see [Scaling](/docs/monitor-pipeline-performance#scaling). ## Integrate with Your App Use the `Search` API endpoint to add the search powered by to your customer-facing app. For detailed instructions, see [Use Your Pipeline in Your Target App](./embed-your-pipeline-in-your-target-app.mdx). Consider also [setting the default pipeline](/docs/how-to-guides/searching-with-your-pipeline/set-default-pipeline.mdx) to which you want to route all traffic. offers a dedicated API endpoint for this. If you need to improve or change your pipeline, you can use this endpoint to seamlessly redirect traffic to another pipeline without your users noticing. Ensure the pipeline you plan to use is set to the *Production* service level. This ensures proper scaling and reliability. To learn more, see [Pipeline Service Levels](/docs/concepts/about-pipelines/about-pipelines.mdx#pipeline-service-levels). ## Collect Feedback Gathering user feedback helps you assess your pipeline's performance. Ensure your users have the opportunity to let you know what they think about your app. You can use the [add feedback endpoint](/docs/collect-feedback#setting-up-a-feedback-system-in-production) to import all the feedback into and [analyze it](/docs/collect-feedback#analyzing-feedback) there. ### Set Expectations Be transparent with your users about how your system works. This includes the boundaries it may have, what type of queries it can handle, where the answers come from (your documents only or the model’s general knowledge), and the like. For more guidance, see [Guidelines for Onboarding Your Users](/docs/how-to-guides/evaluating-your-pipeline/guidelines-for-onboarding-your-users.mdx). ### Start Small Consider releasing the system to a small number of users first. Their feedback will be crucial in determining if your system lives up to their expectations or if you need to improve it some more. Once the initial users are happy with the performance, you can slowly expand the system’s availability. ## Iterate Developing a search system doesn’t end when you release the app. It’s an iterative cycle of monitoring, collecting feedback, and making improvements. Embracing this iterative process will help you evolve the system in alignment with user needs and expectations. --- ## Trace with Langfuse Monitor your pipelines with Langfuse. *** ## About This Task Langfuse is a powerful tool for observability and tracing in complex AI workflows. It captures detailed traces of your pipeline operations, making it easier to debug, monitor, and improve your applications. The integrates with Langfuse using the `LangfuseConnector`. To get started, connect the platform to Langfuse with your API key. Then, simply add the `LangfuseConnector` to your pipelines to start collecting and sending traces to Langfuse. ## Prerequisites - You need the Langfuse public and secret API keys. You can obtain them from your Langfuse project settings. You must create new keys as the secret key can only be viewed and copied once, during creation. - Create two secrets: - One for the Langfuse secret key. Call this secret `LANGFUSE_SECRET_KEY`. - One for the Langfuse public key. Call this secret `LANGFUSE_PUBLIC_KEY`. For more information on secrets, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) and [Secrets and Integrations](/docs/concepts/secrets-and-integrations.mdx). ## Use Langfuse 1. Connect to Langfuse by creating two Langfuse secrets: 1. In , click your profile icon in the top right corner and choose *Settings*. 2. Depending on the scope of the secrets, go to *Workspace* or *Organization* secrets. 2. Click **Create Secret**. 3. Copy the secret key from your Langfuse project and paste it into the *Value* field. 4. Type `LANGFUSE_SECRET_KEY` as the secret key and save the secret. 5. Click **Create Secret**. 6. Copy the public key from your Langfuse project and paste it into the *Value* field. 7. Type `LANGFUSE_PUBLIC_KEY` as the secret key and save the secret. 2. Add the `LangfuseConnector` component to the pipeline you want to trace but do not connect it to any other component. 3. Set the `name` parameter in `LangfuseConnector` to your pipeline name and save the pipeline. When you run a query with this pipeline, its traces will appear in your Langfuse project under _Traces_. ## Example This is an example of a RAG pipeline with Langfuse tracing enabled. `LangfuseConnector` is in the pipeline but it's not connected to any other component:
YAML configuration ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: search_internal_it description: >- Search Acme Corp's internal IT documentation. Use this tool for questions about internal IT policies, procedures, and processes—such as requesting software licenses, getting VPN access, IT support escalation, new employee IT setup, or any company-specific IT how-tos. input_mapping: filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources query: - chat_summary_llm.question output_mapping: chat_summary_llm.last_message: updated_query meta_field_grouping_ranker.documents: documents qa_llm.messages: messages pipeline: pipeline_output_type: chat components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: internal-it-docs max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 fuzziness: 0 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: tabular_joiner.documents: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents chat_summary_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: {% endmessage %} required_variables: "*" streaming_callback: qa_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question.text }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: multi_file_converter.documents receiver: meta_field_grouping_ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: chat_summary_llm.last_message receiver: retriever.query - sender: chat_summary_llm.last_message receiver: ranker.query - sender: chat_summary_llm.last_message receiver: qa_llm.question - sender: meta_field_grouping_ranker.documents receiver: qa_llm.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: {} outputs_to_state: {} _meta: name: search_internal_it description: >- Search Acme Corp's internal IT documentation. Use this tool for questions about internal IT policies, procedures, and processes—such as requesting software licenses, getting VPN access, IT support escalation, new employee IT setup, or any company-specific IT how-tos. tool_id: pipeline_version_id: 5916d707-f550-4b0a-a4d1-6be06a471f98 - type: haystack.tools.pipeline_tool.PipelineTool data: name: search_vendor_docs description: >- Search vendor software documentation. Use this tool for questions about how to use specific applications and products—such as Zoom features, Microsoft 365, setting up email on mobile, or any other software how-to questions. input_mapping: filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources query: - chat_summary_llm.question output_mapping: chat_summary_llm.last_message: updated_query meta_field_grouping_ranker.documents: documents qa_llm.messages: messages pipeline: pipeline_output_type: chat components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: vendor-documents max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 fuzziness: 0 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: tabular_joiner.documents: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents chat_summary_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: {% endmessage %} required_variables: "*" streaming_callback: qa_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question.text }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: multi_file_converter.documents receiver: meta_field_grouping_ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: chat_summary_llm.last_message receiver: retriever.query - sender: chat_summary_llm.last_message receiver: ranker.query - sender: chat_summary_llm.last_message receiver: qa_llm.question - sender: meta_field_grouping_ranker.documents receiver: qa_llm.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: {} outputs_to_state: {} _meta: name: search_vendor_docs description: >- Search vendor software documentation. Use this tool for questions about how to use specific applications and products—such as Zoom features, Microsoft 365, setting up email on mobile, or any other software how-to questions. tool_id: pipeline_version_id: c164dc6d-3b28-406e-8766-a47b19cbee65 system_prompt: >- {% message role="system" %} You are an IT helpdesk assistant for Corp. You help employees solve IT problems and answer questions about IT processes and software. You have two tools: - search_internal_it: Use this for questions about Acme Corp's internal IT policies and procedures—requesting software, getting VPN access, IT support processes, internal how-tos. - search_vendor_docs: Use this for questions about how to use software products—Zoom, Microsoft 365, and other applications. When a question involves both internal processes and software (for example, "I can't connect to Teams because my VPN is blocking it"), use both tools before answering. Base your answer only on the information you find. Cite which documents you used. If you can't find the answer in either knowledge base, say so clearly and tell the employee to contact the IT helpdesk directly at helpdesk@acmecorp.internal. {% endmessage %} user_prompt: required_variables: exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: LangfuseConnector: type: haystack_integrations.components.connectors.langfuse.langfuse_connector.LangfuseConnector init_parameters: name: helpdesk-agent public: false public_key: type: env_var env_vars: - LANGFUSE_PUBLIC_KEY strict: false secret_key: type: env_var env_vars: - LANGFUSE_SECRET_KEY strict: false httpx_client: span_handler: host: langfuse_client_kwargs: max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages filters: [] files: [] outputs: answers: documents: messages: Agent.last_message ```
--- ## Trace Your Pipelines Understand, analyze, and troubleshoot your AI pipelines using logging features and integrated services. *** ## Tracing vs Debugging Tracing and debugging both help you understand how your pipeline runs, but they serve different purposes. Tracing captures the full journey of a query — from the user's input through each processing step to the final result. A trace usually includes timestamps, the original query and its transformations, generated embeddings, retrieved documents, scoring and ranking decisions, as well as any errors or latency issues. Tracing shows how data flows through the system and when each step occurs, giving you a clear picture of what happened end to end. Tools like Langfuse or Weave make this information easy to visualize and explore. Debugging is about getting to the root of problems. It involves analyzing detailed logs to pinpoint errors, misconfigurations, or unexpected behavior. While tracing shows you the "what" and "when," debugging helps you uncover the "why." AI-powered applications are often complex and opaque, making it hard to understand what’s happening under the hood. When something goes wrong, tracing and debugging let you lift the veil. They’re essential for fixing issues, improving performance, and gaining insight into how your models behave. Whether you're tracking down high latency, investigating odd query results, or exploring search patterns, these tools give you the visibility you need to take action. ## Tools for Debugging - Pipeline logs: Capture operational details, such as the component that generated the log, log level, timestamp, and log message. They're available in the Builder on the Analytics tab, but also after running the pipeline in Builder or Playground. - Pipeline debugger: Offers live component-level logs available from Builder. - Remote debug with a VS Code tunnel. ## Tools for Tracing Use integrated services to trace your pipelines: - **Langfuse**: Provides deep tracing for application-level observability, including detailed spans, latency tracking, and cross-service dependencies. - **Weights & Biases Weave**: Captures ML-specific telemetry to help you track your pipeline's latency, token-count, and more. ## Debug Your Pipelines See the following instructions, depending on how you want to debug: - Debug with logs - Debug remotely - Debug with Pipeline Builder ## Trace Your Pipelines - To trace with Weights & Biases, see [Use Weights & Biases Weave](./use-weights-and-biases.mdx) - To trace with Langfuse, see [Trace with Langfuse](./trace-with-langfuse.mdx) --- ## Understand Your Pipeline Usage You can monitor your current pipeline usage, pipeline hours, and document storage units (DSU) anytime on the Usage dashboard. *** :::info Permissions You must be an Organization Admin to view the Usage dashboard. ::: ## Navigating the Usage Dashboard All your usage information is visible on the Usage dashboard, which you can access from organization settings: 1. Click your profile icon and choose *Settings*. 2. Go to *Organization>Usage*. The top of the dashboard shows a summary of all the information. To see how the data breaks down by pipeline, check the table at the bottom of the dashboard. In the summary, you can check the following information: ### 1. Your Organization Your organization name and time frame for the usage data. ### 2. Credits Credits are units that represent the number of hours your pipelines were deployed or your indexes were processing files. This includes pipelines that were deleted but contributed to credits usage during this usage cycle. One credit is one hour of your pipelines being deployed or your indexes processing files. You consume credits when: - Your pipeline is deployed and active. - Your index is actively processing files. No credits are consumed when: - Your pipeline is deployed but inactive, on standby. - Your index is enabled but is not indexing any files as indexing is complete. Note that every time you upload a file, the index processes it, which counts toward credit consumption. #### Production and Development Pipelines Your pipelines can be either production or development. This affects the number of replicas they use and the number of credits they consume. You can configure the number of replicas and the idle timeout in pipeline settings. - Production pipelines have at least one replica running by default and scale up to 10 with heavy traffic. The more replicas running, the more credits you use. - Development pipelines have no replicas by default. For every hour a development pipeline is deployed and active, you use one credit. For details on service levels and how to change them, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx).
What Changed: Credits vs Production and Development Hours Previously, we tracked deployment hours separately for production and development pipelines. This included indexing time, as indexes were tied to query pipelines. Now, we've simplified things. We no longer distinguish between development and production hours. Instead, we measure all active deployment time and all indexing activity in credits: - One credit per hour per active replica - One credit per hour of indexing
#### Estimating Your Credit Usage When planning your credit usage, it's helpful to understand how credits are consumed across different parts of the system. ##### Query Pipelines Credits for query pipelines are based on how long your pipeline is actively deployed and how many replicas it uses. - Development pipeline: 1 credit per hour (no replicas by default) - Production pipeline: 1 replica by default = 1 credit per hour minimum If your production pipeline scales due to high traffic, credit usage increases proportionally with the number of active replicas (up to a maximum of 10). You can configure the minimum and maximum number of replicas in the pipeline's **Settings** tab. ##### Indexing Credits for indexes are only used when files are being processed. You don’t need to index the same data more than once. After indexing, you can reuse that data across different query pipelines without additional credit costs. Several factors can affect how many credits indexing will use: - Size and number of files: Larger and more files take longer to process. - Index configuration: Preprocessing steps like OCR or generating metadata with a language model increase processing time. - Upload pattern: Uploading files in a single batch or in several large batches is more efficient. Uploading files one-by-one with long gaps in between may add warm-up time. - Embedding model: The dimensionality of the embedding model, the number of models used, and whether they're hosted locally or accessed via API can impact speed and credit usage. ##### Example Credit Usage Here are some rough estimates for how many credits are used by our standard index templates. This scenario assumes: - 100 files in a mix of formats (TXT, HTML, XLSX, PDF, DOCX, CSV) - All files uploaded together in one batch | Index Template | Approximate Credits Used | | :----------------------- | :----------------------- | | Standard Index (English) | 0.03 | | AI-Generated Metadata | 0.06 | These figures can vary depending on your specific setup, but they offer a starting point for estimating costs. ### 3. Document Storage Units Document Storage Units (DSU) show how much vector storage you're using for your indexed documents. The DSU count on the Usage page reflect the current state. They can go up or down as you add or remove documents. When you upload and index your files, we split them into smaller pieces called _documents_. These documents are stored and your DSU count depends on two key factors: - How many documents your files are split into. - The size (dimensionality) of the embedding model used to process them. The more documents or the larger the model, the more storage units you use. #### Calculating DSUs To calculate DSUs, we multiply the number of stored documents by a multiplier that reflects the embedding model's dimensionality: - A standard embedding model with 768 dimensions uses a multiplier of 1. - A larger model with 1,536 dimensions uses a multiplier of 2, meaning it needs twice as much storage. - If you use keyword-based search or don't use vector storage, the multiplier is just 0.2, so it uses much less storage. ##### Example Say you upload 5,000 files which are split into 83,697 documents: - With the standard embedding model (768 dimensions): `83,697 documents × 1 = 83,697 storage units` - With a larger model (1,536 dimensions): `83,697 documents × 2 = 167,394 storage units` - With keyword search only or no vector storage: `83,697 documents × 0.2 = 16,739.4 storage units` #### Optimizing Storage Usage As you near your storage capacity, you can reduce storage consumption by: - Deleting duplicate files. - Reducing irrelevant files, starting from the largest ones. Detecting irrelevant files is specific to your use case. You can use the [Search History](/docs/api/main/search-history-api-v-1-workspaces-workspace-name-search-history-get.api.mdx) endpoint to check user queries, files, and documents used. - Adjusting settings in DocumentSplitter: - If your `split_overlap` setting is high, consider decreasing it. - If your `split_length` setting is low, try increasing it. Remember that it's important to avoid too large values to prevent Retriever and Generator components from cutting the documents. ### 4. Usage Per Pipeline or Index At the bottom of the page, you can check the detailed usage per pipeline or index. You can check the number of credits used and the workspace it's in. Indexes and pipelines that were deleted but contributed to usage in the current cycle are greyed out. --- ## Trace with Weights & Biases Weave Use the Weights & Biases (W&B) Weave service for tracing and monitoring your LLM apps. *** ## About This Task integrates with the W&B Weave, a powerful tool for tracking and evaluating LLM-based applications. After connecting to W&B with your W&B API key, you can add the `WeaveConnector` component to your pipelines. This component collects your pipeline's traces and sends them to W&B for analysis. ## Prerequisites You need an API key from Weights & Biases. You also need to install W&B Weave. For details, see the [W&B Weave documentation.](https://weave-docs.wandb.ai/quickstart#1-install-weave-and-create-an-api-key) ## Use W&B Weave 1. Connect to Weights & Biases through the Integrations page. You can set up the connection for a single workspace or for the whole organization:
Add Weave Integration
2. Add the `WeaveConnector` component to your pipeline, but do not connect it to any other component. 3. Set the `pipeline_name` parameter in `WeaveConnector` to your pipeline's name. The value you provide for `pipeline_name` will be used as the name of your Weave tracing project in W&B. The W&B tracing project is automatically created when you query the pipeline for the first time. You can view it on the [W&B dashboard](https://wandb.ai/) under _Projects_. Using a pipeline name helps you easily identify which pipeline the traces belong to, especially when managing multiple projects. ## Example This is an example of an agent with `WeaveConnector`. The component is in the pipeline, but it's not connected to any other component. That's enough to send the pipeline traces to Weights & Biases: ```yaml components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: search_internal_it description: >- Search Acme Corp's internal IT documentation. Use this tool for questions about internal IT policies, procedures, and processes—such as requesting software licenses, getting VPN access, IT support escalation, new employee IT setup, or any company-specific IT how-tos. input_mapping: filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources query: - chat_summary_llm.question output_mapping: chat_summary_llm.last_message: updated_query meta_field_grouping_ranker.documents: documents qa_llm.messages: messages pipeline: pipeline_output_type: chat components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: internal-it-docs max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 fuzziness: 0 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: tabular_joiner.documents: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents chat_summary_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: {% endmessage %} required_variables: "*" streaming_callback: qa_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question.text }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: multi_file_converter.documents receiver: meta_field_grouping_ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: chat_summary_llm.last_message receiver: retriever.query - sender: chat_summary_llm.last_message receiver: ranker.query - sender: chat_summary_llm.last_message receiver: qa_llm.question - sender: meta_field_grouping_ranker.documents receiver: qa_llm.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: {} outputs_to_state: {} _meta: name: search_internal_it description: >- Search Acme Corp's internal IT documentation. Use this tool for questions about internal IT policies, procedures, and processes—such as requesting software licenses, getting VPN access, IT support escalation, new employee IT setup, or any company-specific IT how-tos. tool_id: pipeline_version_id: 5916d707-f550-4b0a-a4d1-6be06a471f98 - type: haystack.tools.pipeline_tool.PipelineTool data: name: search_vendor_docs description: >- Search vendor software documentation. Use this tool for questions about how to use specific applications and products—such as Zoom features, Microsoft 365, setting up email on mobile, or any other software how-to questions. input_mapping: filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources query: - chat_summary_llm.question output_mapping: chat_summary_llm.last_message: updated_query meta_field_grouping_ranker.documents: documents qa_llm.messages: messages pipeline: pipeline_output_type: chat components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: vendor-documents max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 fuzziness: 0 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: tabular_joiner.documents: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents chat_summary_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: user_prompt: >- {% message role="user" %} You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: {% endmessage %} required_variables: "*" streaming_callback: qa_llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question.text }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: multi_file_converter.documents receiver: meta_field_grouping_ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: chat_summary_llm.last_message receiver: retriever.query - sender: chat_summary_llm.last_message receiver: ranker.query - sender: chat_summary_llm.last_message receiver: qa_llm.question - sender: meta_field_grouping_ranker.documents receiver: qa_llm.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: {} outputs_to_state: {} _meta: name: search_vendor_docs description: >- Search vendor software documentation. Use this tool for questions about how to use specific applications and products—such as Zoom features, Microsoft 365, setting up email on mobile, or any other software how-to questions. tool_id: pipeline_version_id: c164dc6d-3b28-406e-8766-a47b19cbee65 system_prompt: >- {% message role="system" %} You are an IT helpdesk assistant for Corp. You help employees solve IT problems and answer questions about IT processes and software. You have two tools: - search_internal_it: Use this for questions about Acme Corp's internal IT policies and procedures—requesting software, getting VPN access, IT support processes, internal how-tos. - search_vendor_docs: Use this for questions about how to use software products—Zoom, Microsoft 365, and other applications. When a question involves both internal processes and software (for example, "I can't connect to Teams because my VPN is blocking it"), use both tools before answering. Base your answer only on the information you find. Cite which documents you used. If you can't find the answer in either knowledge base, say so clearly and tell the employee to contact the IT helpdesk directly at helpdesk@acmecorp.internal. {% endmessage %} user_prompt: required_variables: exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: WeaveConnector: type: haystack_integrations.components.connectors.weave.weave_connector.WeaveConnector init_parameters: pipeline_name: helpdesk-agent weave_init_kwargs: max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages filters: [] files: [] outputs: answers: documents: messages: Agent.last_message ``` In Pipeline Builder, you simply drag the component from the Connectors group, drop it on the canvas, and pass the name of the pipeline you want to trace in the `pipeline_name` parameter. `WeaveConnector` is not connected to any component. ## Related Information - [WeaveConnector](/docs/reference/pipeline-components/integrations/weave/WeaveConnector.mdx) - [Trace Your Pipelines](/docs/how-to-guides/productionizing-your-pipeline/trace-your-pipelines.mdx) --- ## Test Your Pipeline in Playground Time to test your pipeline! *** ## About This Task You can run queries with your pipeline and check whether the responses match the quality you expect. You can also use the Playground to collect feedback from users; they can add feedback to each response. You can then check this feedback on the Pipeline details page. For more information, see [Collect User Feedback](/docs/how-to-guides/evaluating-your-pipeline/collect-feedback.mdx). ### Upload Files You can upload files directly in Playground. If the workspace doesn't contain any files, the pipeline runs only on the files you upload. If the workspace already has files, the pipeline uses both the workspace files and the ones you uploaded. To support file uploads in Playground, make sure the `Input` component is configured to receive files. We also recommend adding Converters and PreProcessors that can handle the types of files you plan to upload, just like you would in an index. Without them, the uploaded files won't be preprocessed. :::info Pipeline Templates If you're using a pipeline built with one of our templates, all the necessary components are already included. ::: ### Download Generated Files If your pipeline generates files as output, for example processed documents, reports, or other file types, you can download them from the Playground. Open the sources section in the answer and download the file. ### Pipeline Output Type You can indicate the output type of your pipeline in pipeline YAML to make sure Playground displays the results in the best possible way. Add `piepline_output_type` to the YAML and set it to one of these values: - `chat` - `generative` - `extractive` - `document` For details, see [Set Pipeline Output Type](/docs/how-to-guides/designing-your-pipeline/set-additional-params/set-pipeline-output.mdx). ### Logs Playground shows logs for each query you run. You can click the Debug icon to view output logs for each pipeline run. These include component parameters, queries, and answers. ## Prerequisites - If you're asking your colleague to test your pipeline, have a look at [Guidelines for Onboarding Your Users](/docs/how-to-guides/evaluating-your-pipeline/guidelines-for-onboarding-your-users.mdx). - You must have a deployed, active pipeline. ## Run Queries in the UI 1. Log in to . 2. Click **Playground**. 3. Choose the pipeline and version you want to test. By default, the deployed version or the latest saved version is used. 4. To set filters, click **Configuration**. _Note_: Filters are available only if the files have metadata. You can add metadata to your files when you're [uploading](/docs/how-to-guides/working-with-your-data/upload-files.mdx) them. These metadata then act as filters at search time. 5. To upload files, click the paperclip icon in the Search field. 6. To test different settings, use the _Configuration_ option to change component parameters for the query you're asking. Use the format `{ "component_name": { "parameter_name": "parameter_value" }}`. This is useful for trying out different parameter values or testing `ConditionalRouter` routes. For example, you can change the retriever's `top_k` value, like this: 7. Type your query and click **Search**. :::tip Check Sources Expand the Sources (1) section below the search result to view the documents and files it's based on. Click the More actions button (2) next to an answer to view the prompt that was used to generate it: 8. Check the logs generated for the query by clicking the debug icon: ## Run Queries with the REST API Use the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) API endpoint: 1. Go to the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) endpoint documentation page. 2. Enter the necessary parameters: - Type the name of the pipeline to use for the search. - Type the workspace name containing the pipeline you want to use in your target app. - Optionally, add filters. (You can use metadata from your documents as filters to narrow the search. For more information, see [Add Search Filters](../working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx).) - Optionally, specify any runtime parameters. - Type the queries. - In the _Bearer_ field, paste the API key you previously generated. 3. Choose the programming language that you want to use and copy the code. Here's an example request: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/WORKSPACE_NAME/pipelines/PIPELINE_NAME/search \ --header 'accept: application/json' \ --header 'authorization: Bearer api_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4NDU4ZGIyOC1kMTZlLTRkMzAtYTY2OS1lMDg1MDllNDY4YWV8NjQzY2Y5YTlmNzExNDg0MmUwNzk5ZDQ3IiwiZXhwIjoxNzA2Njg2MDUyLCJhdWQiOlsiaHR0cHM6Ly9hcGkuY2xvdWQuZGVlcHNldC5haSJdfQ.wh4_62gBcpfPVwYvrxlLtia7_YRaMpMx00EXWGP18IM' \ --header 'content-type: application/json' \ --data ' { "debug": true, "filters": { "field": "meta.field_name", "operator": "", "value": "field_value" }, "params": { "param1": "value1", "param2": "value2" }, "queries": [ "my query" ] } ' ``` See also [Use Your Pipeline in Your Target App](../productionizing-your-pipeline/embed-your-pipeline-in-your-target-app.mdx) and [Productionizing Your Pipeline](../productionizing-your-pipeline/productionizing-your-pipeline.mdx). ## What's Next You can open or download each document containing the answer. To do that, hover over the More Actions icon next to the document name. You can also copy or download the answer text using the copy and download icons next to the answer. Downloading saves the answer as a Markdown file. You can also give feedback for each answer using the thumbs-up and thumbs-down icons. This will let the pipeline creator know how the pipeline is doing. As the pipeline creator, you can then analyze the feedback on the Pipeline Details page. Click the pipeline name to open it. --- ## Set Default Pipeline(Searching-with-your-pipeline) You can update your pipeline in production without any downtime. Use the `set default pipeline` endpoint to seamlessly direct all traffic to a new pipeline. *** ## About This Task You can set a pipeline as the default for your search by using the [Set Default Pipeline](/docs/api/main/set-default-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-default-post.api.mdx) endpoint. Once you do this, you can simply use `default` as the pipeline name in the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) endpoint. No additional work or app changes are required on your part. This option gives you the flexibility to change the pipeline you use for search in production at any time without disrupting your service. For example, if you need to tweak the pipeline used in production, you can create and test a new one in the background. When it's ready, simply set it as the default pipeline to smoothly redirect traffic to it. :::tip Setting a Default Pipeline Version with the UI You can also set a pipeline version as the default one. For details on how to do this, see [Manage Pipeline Versions](/docs/how-to-guides/designing-your-pipeline/manage-pipeline-versions.mdx). ::: ## Change the Default Pipeline 1. [Create a pipeline](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx) that will replace the pipeline currently running in production. 2. [Deploy the new pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx). We recommend verifying this pipeline's performance by sharing it with other users and collecting feedback. 3. Use the [set default pipeline](/docs/api/main/set-default-pipeline-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-default-post.api.mdx) API endpoint to indicate that you want to use the newly created pipeline in production. This simply routes all queries to the new pipeline without any interruptions. 4. When using the endpoints for search, such as [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx), [Search Stream](/docs/api/main/search-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-stream-post.api.mdx), [Chat](/docs/api/main/chat-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-post.api.mdx), or [Chat Stream](/docs/api/main/chat-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-stream-post.api.mdx), set the pipeline name to `default` in the URL, for example: `https://api.cloud.deepset.ai/api/v1/workspaces/my_workspace/pipelines/default/search`. --- ## Modify Pipeline Parameters at Query Time You can override component parameters set in the pipeline configuration for a specific query. This helps you test different settings without changing the pipeline file. *** ## Parameters You Can Modify At query time, you can modify the `run()` method parameters of the components in your pipeline. To check the parameters you can change for a specific component: 1. Go to the [component documentation](/docs/concepts/about-pipelines/pipeline-components.mdx). 2. Scroll down to the _Run Method Parameter_ section. These are the parameters you can modify at query time. For example, for `DeepsetAnswerBuilder`, you can find the parameters in the [Run Method Parameters](/docs/reference/pipeline-components/data-processing/transform/DeepsetAnswerBuilder.mdx#run-method-parameters) section of the documentation. :::info Component Connections You can't modify component connections at query time. ::: ## Parameter Format Pass parameters as a JSON dictionary using the following format: ```json { "component1_name":{ // this is the name you gave to your component in your pipeline "parameter1_name":"parameter1_value", "parameter2_name":"parameter2_value" }, "component2_name":{ "parameter3_name":"parameter3_value" } } ``` For example, to change the Retriever's `top_k` parameter for a specific query, use this code: ```json { "retriever":{"top_k":5} } ``` :::warning Important The component names must match those defined in your pipeline. The parameters you set must be valid `run()` method parameters for the corresponding components. ::: ## Passing Parameters You can modify parameter values at query time in three ways: - Through the Search API endpoint - Through the Chat Stream API endpoint - In Playground - In a query set for a job - On a shared prototype page - In Prompt Explorer ### Passing Parameters Through the Search API When querying your pipeline with the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx) API endpoint, include the `params` field in your request. Inside `params`, specify the component names and the parameters you want to modify. This is an example request that changes the `embedding_retriever`'s `top_k` to `1` for the query "Who was in the first all-girl jazz bands?": ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/my_workspace/pipelines/my_pipeline/search \ --header 'accept: application/json' \ --header 'authorization: Bearer deepset_API_key' \ --header 'content-type: application/json' \ --data ' { "debug": true, "params": { "embedding_retriever": { "top_k": 1 } }, "view_prompts": false, "queries": [ "who was in the first all-girl jazz bands?" ] } ' ``` ### Passing Parameters Through the Chat Stream API When querying your pipeline with the [Chat Stream](/docs/api/main/chat-stream-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-stream-post.api.mdx) API endpoint, include the `params` field in your request body. This works both for deployed pipelines and for pipelines running in serverless mode (without prior deployment). This is an example request that limits the retriever to one result: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/my_workspace/pipelines/my_pipeline/chat-stream \ --header 'accept: application/json' \ --header 'authorization: Bearer deepset_API_key' \ --header 'content-type: application/json' \ --data ' { "query": "Who was in the first all-girl jazz bands?", "params": { "retriever": { "top_k": 1 } }, "search_session_id": "your-session-id" } ' ``` #### Routing Filters to Components in Serverless Mode When running a pipeline in serverless mode via `chat-stream`, you can also pass Haystack [filters](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx) at query time. For filters to reach the right component, you must add an `inputs` section to your pipeline YAML that maps the `filters` key to the target component input using the format `component_name.input_name`: ```yaml inputs: filters: - retriever.filters ``` You can map filters to multiple components at once: ```yaml inputs: filters: - bm25_retriever.filters - embedding_retriever.filters ``` With this mapping in place, filters you pass in the `chat-stream` request body are forwarded to all listed components: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/my_workspace/pipelines/my_pipeline/chat-stream \ --header 'accept: application/json' \ --header 'authorization: Bearer deepset_API_key' \ --header 'content-type: application/json' \ --data ' { "query": "What did Alice write?", "filters": { "field": "meta.category", "operator": "==", "value": "news" }, "search_session_id": "your-session-id", "serverless": true, "pipeline_version_id": "your-pipeline-version-id" } ' ``` :::warning Important If the `inputs.filters` mapping in your pipeline YAML is malformed (for example, a list entry is missing the dot separator between component name and input name), the request returns a 400 error. Make sure each entry follows the `component_name.input_name` format. ::: ### Passing Parameters in Playground, Shared Prototype, and Prompt Explorer When testing your pipeline in the Playground, you can set runtime parameters in the *Configurations* window. This is the fastest and easiest way to see how different settings affect pipeline results. To update parameters: 1. In , go to **Playground**, **Prompt Explorer**, or open the shared prototype link. 2. If applicable, choose the pipeline you want to test and click the **Configurations** button in the top right corner. 3. In the Configurations window, enter the components and parameters you want to update as a JSON dictionary using this format: `{ "component_name": { "parameter1_name": "parameter1_value" }}`: 4. Type your query and run the search. To compare results, run another search without modifying the parameters. ### Passing Parameters in a Query Set When creating a query set for a job, list the components and parameters you want to change in the `params` column. For details and examples, see [Example query set with parameters](/docs/how-to-guides/working-with-jobs/prepare-a-query-set.mdx). --- ## Create an Index Define the processing steps for your files to prepare them for search. You use Builder to create your indexes. *** ## About This Task You create indexes just like you create pipelines. Indexes are a series of connected components, each performing a preprocessing step on your files. To learn more, see [Indexes](/docs/concepts/indexes/indexes.mdx). Indexes are specific to a workspace. A single query pipeline can use multiple indexes. You can use Builder to design your indexes.
Using Builder
After you save an index, you must enable it to start indexing the files in your workspace. Files uploaded after an index was enabled, are automatically added to the enabled index. The query pipeline can access all files only after indexing is complete. ## Prerequisites - Understanding indexes. To learn more, see [Indexes](/docs/concepts/indexes/indexes.mdx). - Understanding pipelines and components. For details, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). ## Create an Index in Pipeline Builder 1. Log in to , go to **Indexes** and choose **Create Index**. 2. Choose a template to start with or click **Build your own** to create an index from scratch. 3. Give your index a name and add a meaningful description. 4. Click **Create index**. You're redirected to Builder. - If you're creating the index from a template, edit the template if needed and save your index. - If you're creating an index from an empty file, click **Add** to see available components, and: 1. Drag the `Input` component onto the canvas. This is always the first component of an index. It represents the files your index will process. 2. The second component is often `FileTypeRouter`. It's useful if you're planning to index files of different types. You can set it to identify the file type and route it to an appropriate converter. 3. Choose `Converters` for the file types you want to index. You can either search for them or view all converters in *Data Processing > Convert*. 4. Add `Preprocessors` as needed. You can either search for them or view all preprocessors in *Data Processing > Clean & Split*. 5. Connect the components by clicking one component's input and then another component's output. The connection is automatically created and validated. **Tip**: Open the Connections panel at the bottom of the canvas to manage, inspect, and edit component connections. 6. Add `DocumentWriter` as the last component of your index. It writes the processed documents into the document store where a query pipeline can access it. 7. Add a `DocumentStore` that will use this index and connect it to `DocumentWriter`. **Tip**: `OpenSearchDocumentStore` is the core document store. 8. Save your index. # What To Do Next - [Enable the index](./edit-an-index.mdx) to start indexing files. Click **Enable** on the index page. - Add the index to your query pipelines. For details, see [Edit a Pipeline](/docs/how-to-guides/designing-your-pipeline/edit-a-pipeline.mdx) or [Create a Pipeline in Pipeline Builder](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx). - Click the index name to open the Index Details page where you can see the index information, logs, and processed files. --- ## Edit an Index Update your index. *** ## About This Task You can update draft indexes that aren't enabled. Once an index is enabled, it becomes read-only. To make changes to an enabled index, you have two options: - **Duplicate the index**, update the copy, and keep the original index enabled and unaffected. When you're ready, enable the updated copy and connect your pipelines to it. This way, you can switch without any downtime. We recommend this approach. - **Disable the index**, which removes all associated indexing data and temporarily prevents any query pipelines from accessing it. With this approach, you must wait until the updated index is re-enabled and indexing is complete before running queries again. ## Edit an Index in Pipeline Builder 1. Log in to and open _Indexes_. 2. Find the index you want to update and make sure it's disabled. 3. Click the index name and switch to **Build**. Here, you can update the index components and connections. ## Duplicate an Index Duplicating creates a copy of an index with its YAML configuration. Use this when you want to update an enabled index without downtime — duplicate it, update the copy, then enable the copy and connect your pipelines to it. 1. Log in to and open _Indexes_. 2. Find the index you want to copy, click More Actions next to it, and choose *Duplicate*. 3. In the *New pipeline name* field, enter a name for the copy. The default name is `{source-name}-copy`. 4. Click **Duplicate**. You're taken to Pipeline Builder where you can edit the new index. If an index with the name you entered already exists, an inline error appears — enter a different name and try again. ## What To Do Next Once your index is updated, [enable it](./enable-an-index) and wait until indexing finishes. Link your pipelines to the updated index. For details, see [Edit a Pipeline](/docs/how-to-guides/designing-your-pipeline/edit-a-pipeline.mdx). --- ## Enable an Index Enable an index to start indexing files. *** ## About This Task When you create an index, it's disabled by default. You must enable it to start indexing files and make them searchable for query pipelines using this index. ## Prerequisites A draft index. ## Enable an Index 1. Log in to and go to _Indexes_. 2. Find the index you want to enable, click More actions next to it, and choose _Enable_. 3. Wait until the index status changes to *indexed*. When this happens, the files are ready for search and you can use this index in your query pipelines. ## What To Do Next Add the index to your pipelines. You can do this by selecting this index on the Document Store component card in Pipeline Builder. To check the details of the index, including the logs and file status, click the index name. To learn what happens if you update files with an enabled index, see [Indexes](/docs/concepts/indexes/indexes.mdx#file-updates). --- ## Enable GPU Acceleration for Indexes By default, indexes run on CPU. You can enable GPU acceleration for an index to speed it up. This is especially useful for pipelines that include components that run faster on a GPU, like `DoclingConverter` or `SentenceTransformersDocumentEmbedder`. *** ## About This Task When you enable GPU acceleration, the index checks whether a component needs a GPU and assigns one automatically. GPUs are only used when required and are not reserved for the entire index processing. If GPU acceleration is disabled and your index includes components that rely on a GPU, those components run on the CPU instead. This can slow down processing and may cause timeouts, especially for larger or more complex indexes. ## Enable GPU Acceleration 1. Go to **Indexes** and click the index you want to enable GPU acceleration for. This opens the Builder. 2. Open the **Settings** tab and click the GPU Acceleration toggle to turn it on. --- ## PreProcessing Data with Pipeline Components Learn about optimal ways to prepare your data using pipeline components available in . If you need tips and guidelines, you'll find them here. *** ## Indexes for Preprocessing An index converts your files to documents, preprocesses them, and finally stores them in a document store. The query pipeline can then use the documents from the document store to resolve queries. For details, see [Indexes](/docs/concepts/indexes/indexes.mdx). offers preprocessing components that you can add to your index. When you enable the index, your files are automatically converted, split, and cleaned. Templates available in include indexes that preprocess TXT, PDF, MD, DOCX, PPTX, XLSX, XML, CSV, HTML, and JSON files out of the box. For other formats, you may need to preprocess outside of . ### Integrations for Processing Data #### Unstructured You can use [unstructured.io](https://unstructured.io/) through [UnstructuredFileConverter](https://docs.haystack.deepset.ai/docs/unstructuredfileconverter) to preprocess your files. To learn how to do this, see [Use Unstructured to Process Documents](../working-with-indexes/use-unstructured.mdx). #### Azure Document Intelligence Use `AzureOCRDocumentConverter` to take advantage of Azure Document Intelligence preprocessing services. For details, see [Use Azure Document Intelligence](./use-azure-document-intelligence.mdx). ## How to Prepare Your Files Here's an outline of how to plan file preprocessing: Your files determine which components to use in the index: - If all your files are of one type, use a file converter appropriate for handling this type as the first component in your index. For supported converters, see Converters. - If you have multiple file types, use `FileTypeRouter` as the first component in your index and connect it to the converters for all file types you need. FileTypeRouter classifies your files based on their extension and sends them to the converter that can best handle them. :::tip MultiFileConverter Instead of using multiple converters, you can use `MultiFileConverter` to convert all your files at once. For details, see [MultiFileConverter](/docs/reference/pipeline-components/data-processing/convert/MultiFileConverter.mdx). ::: The converter's task is to convert your files into documents. However, the documents you obtain this way may not be of the optimal length for the retriever you want to use and may still need cleaning up. `PreProcessors` are the components that handle the cleaning and splitting of documents. They remove headers and footers, which is useful for retaining the flow of sentences across pages; they delete empty lines and split your documents into smaller chunks. Smaller documents speed up your pipeline. They're also optimal for vector retrievers, which often can't handle longer text passages. We recommend 100-word splits for vector retrievers. Keyword retrievers can work on slightly longer documents of around 200-300 words. Use these suggestions as a starting point for your index. You may need to experiment with your settings to reach the optimal values for your use case. ## Pipeline Components for Preprocessing Components are very flexible, and you can use them in all types of pipelines, but several are typically used for indexing. Have a look at this table to help you choose the right components: | Preprocessing Step | Component That Does It | |-------------------|------------------------| | Sort files by type and route them to appropriate converters for the file type. | `FileTypeRouter` | | Convert a file to a document object. You can choose a converter that matches your file types.For file types for which a converter is unavailable, we recommend preprocessing your files outside of . | `Converters` | | Validate text language based on the ISO 639-1 format. | `Converters` | | Remove numeric rows from tables. | `Converters` | | Add metadata to the returned document. | `Converters` | | Split long documents into smaller ones. | `DocumentSplitter` | | Get rid of headers, footers, whitespace, and empty lines. | `DocumentCleaner` | | Extract text and tables from PDF, JPEG, PNG, MBP, and TIFF files. | `Converters` | | Extract content using https://unstructured.io/ API. | `UnstructuredFileConverter` | | Extract entities from documents in the document store and add them to the documents' metadata. | `NamedEntityExtractor` | | Calculate embeddings for documents. | `DocumentEmbedders` | | Write cleaned and split documents into the document store. | `DocumentWriter` | --- ## Use Azure Document Intelligence Convert files to documents using the Azure's Document Intelligence service. *** ## About This Task Azure Document Intelligence extracts text from files in the following formats: - JPEG - PNG - BMP - TIFF - DOCX - XLSX - PPTX - HTML For more details on the service capabilities, see the [Azure Document Intelligence](https://azure.microsoft.com/en-us/products/ai-services/ai-document-intelligence) website. For a list of models you can use to process your files, see [model overview](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/choose-model-feature?view=doc-intel-4.0.0) in Document Intelligence documentation. ## Prerequisites You need an API key from your Azure account with the Document Intelligence resource. For details, see [Get started with Document Intelligence](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api?view=doc-intel-4.0.0&pivots=programming-language-csharp) in Azure documentation. ## Use Azure Document Intelligence First, connect to Azure Document Intelligence through the Integrations page. You can set up the connection for a single workspace or for the whole organization: Then, add the `AzureOCRDocumentConverter` component to your index. ## Usage Examples This is an example of an index that uses Azure's OCR converter to process PDF files: ```yaml Index components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 ocr_converter: #This is the Azure OCR converter type: haystack.components.converters.azure.AzureOCRDocumentConverter init_parameters: api_key: {"type": "env_var", "env_vars": ["AZURE_AI_API_KEY"], "strict": false} endpoint: "YOUR-ENDPOINT" model_id: "prebuilt-read" page_layout: "natural" markdown_converter: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: txt # Extract text from HTML. You can also also choose "markdown" target_language: null # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: false # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: {} pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: deepset_cloud_custom_nodes.preprocessors.document_splitter.DeepsetDocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: True language: en document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/e5-base-v2" writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: ocr_converter.sources # Azure converter receives PDF files - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: ocr_converter.documents #It then sends the resulting documents to DocumentJoiner receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents max_loops_allowed: 100 inputs: # Define the inputs for your index files: "file_classifier.sources" # This component will receive the files to index as input ``` --- ## Use Unstructured to Process Documents Convert files to documents using the Unstructured API. *** Unstructured provides tools to extract content from files and transform it into clean documents ready to be chunked and embedded. For a list of supported formats, see [Unstructured documentation](https://docs.unstructured.io/api-reference/api-services/overview#supported-file-types). You can use free Unstructured API or paid Unstructured Serverless API. ## Prerequisites You need an API key to your Unstructured account. ## Use Unstructured First, connect to Unstructured through the Integrations page. You can set up a connection for a single workspace or for the whole organization: Then, add the `UnstructuredFileConverter` component to your index. ## Usage Examples This is an example of an index that uses Unstructured API to process files: ```yaml Index components: # ... unstructured_converter: type: haystack_integrations.components.converters.unstructured.converter.UnstructuredFileConverter init_parameters: {} splitter: type: deepset_cloud_custom_nodes.preprocessors.document_splitter.DeepsetDocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: True language: en document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/e5-base-v2" writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: OVERWRITE connections: # Defines how the components are connected - sender: unstructured_converter.documents receiver: splitter.documents - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents max_loops_allowed: 100 inputs: # Define the inputs for your index files: "file_classifier.sources" # This component will receive the files to index as input ``` --- ## Create a Job Jobs are configurable workflows that run on your files using a pipeline you choose. Currently, supports a job for batch question answering. *** ## About This Task A job runs once on all files in your workspace. You can see the results on the job details page and you can easily share them as a formatted HTML page. A job processes 10 queries at once to ensure high speed. :::info Jobs can only use pipelines that return answers, such as RAG or extractive question answering pipelines, or chat. Jobs that run for more than 12 hours are automatically stopped. ::: ## Prerequisites [Prepare a Query Set](./prepare-a-query-set.mdx). ## Create a Job 1. In the navigation, go to _Jobs > New Job_. 2. Choose the job type, and click **Next**. Currently, only batch question answering is supported. You can run the queries on your files: 1. Run once: You search for an answer to each query among all files. As a result, you get one answer per query. 2. Repeat queries per file: The queries are applied to each file. As a result, you get as many answers as there are files. 3. Upload your query set or choose a previously uploaded one, and move on to the next step. 4. Choose the pipeline you want to use to process the queries. If the pipeline is not indexed, starting the job will trigger indexing. Jobs can only use pipelines that return answers, like RAG, chat, or extractive question answering. 5. Give your job a name and choose one of the following: 1. To start the job now, click **Start Job**. The job starts running. It continues running even if you leave the page. 2. To save the job as a draft, click **Save as Draft**. You can run it later from the Jobs page. ## What To Do Next Click the job name to view its details. You can check the details of each query, such as the answer, the prompts used, the parameters, and more. You can also generate a link to the results page and [share](./share-a-job.mdx) it with others. --- ## Prepare a Query Set Query sets are CSV files containing the queries you want the job to process, any filters you want to use, and the configuration for displaying the results. See an example query set and learn how to create your own. *** ## Query Set Format Your query set must be a UTF-8 encoded CSV file that contains the following columns: | Column Name | Content | Required? | |-------------|---------|-----------| | query | The actual query text. | Yes | | filters | The filters used to narrow down the files processed during a job based on file metadata. A filter is used for the query listed in the same CSV row and is applied to all files. For example, to execute a specific query exclusively on files categorized as "report", include the filter `{"field": "category", "operator": "==", "value": "report"}` in the corresponding column. (Assuming your files have a "category" metadata field with the value "report".)You can use filters to run the same query on different files. To do this, copy your query to a new row and set a filter indicating the file you want to run it on.For more information, see [Filtering Logic](/docs/how-to-guides/working-with-your-data/working-with-metadata/filtering-logic.mdx). | No | | query label | The name under which you want this query to be displayed on the results page. For example, for a query "Who is the chairman?", you may want the label to be just "Chairman". | No | | group name | The name of a query group you want this query to be displayed in on the results page. You can group your queries to make the results easier to interpret. For example, for a query like "What's the property https://www.iana.org/assignments/media-types/application/vnd.openxmlformats-officedocument.wordprocessingml.document?", a group name could be "Address". | No | | params | Additional parameters you can pass to individual pipeline components at search time. These parameters override the parameters provided in the pipeline configuration. For a list of parameters you can use, check the component's `run()` method parameters in [Haystack's API documentation](https://docs.haystack.deepset.ai/reference/audio-api). | No | For help on saving files as UTF-8 encoded, see [How to save CSV files as UTF-8 encoded](https://www.webtoffee.com/how-to-save-csv-excel-file-as-utf-8-encoded/). ### Template Here’s the query set template we prepared to help you get started: [Template for batch QA](https://docs.google.com/spreadsheets/d/1Wq8VLuKidD-rHBeOognzTU-4GnRukeiHXBUnADCHMNo/edit#gid=0). ### Example Query Sets #### With Filters and Labels This query set applies filters to specify the file where the model looks for the answer to a particular query. It also assigns query labels to the queries and groups them: And here’s what it looks like on the results page: Query labels are shown instead of whole query texts, and they’re grouped by the group names you assigned to them in the CSV. When sharing the job, you can also add a title that's visible at the top and bottom of the page. #### Without Labels This query set uses filters to narrow down the search but doesn't group the queries or assign labels to them; that's why the _query label_ and _group name_ columns are empty. This is what it looks like on the results page: The queries are displayed exactly as they were in the _query_ column of the query set; they're not grouped. The page uses the default title _Job Report_, but because it wasn't specified on the Share Job modal, it's not showing at the top of the page. #### One Query Against Multiple Files You can ask the same query against multiple files in your workspace. To do this, add the same query in a new row and specify a different file name in the Filters column, like this: On the results page, you'll simply see the query repeated, with a different answer each time: #### With Parameters This query set overrides the ranker's `top_k` and the llm's `temperature` parameters from the pipeline configuration. If a query includes these parameters, the will use the values from the query set instead. On the results page, you'll see queries with answers, but if you click the job name and check the job details, you'll see the parameters used for each query. ## Upload a Query Set You add your query set when creating a job. You can then also select previously uploaded query sets. For details, see [Create a Job](./create-a-job.mdx). --- ## Share a Job You can share a job's results with your colleagues as a neatly formatted HTML page that requires no login, or you can download them to your computer. *** ## About This Task Once a job is completed, you can generate a link to the page with the results and share it with others. They can view the page without logging in to or setting up an account. But you can also restrict the shared job to logged in users from your organization. You control when the link expires and whether the viewers can see the files the job ran on. You can revoke access to the link at any time by deleting it. ### Formatting Results You control the formatting of queries on the shared results page through the query set CSV file, where you can assign labels to the queries and group them. The shared page uses query labels instead of full query texts and groups the queries by group names you assigned to them. When sharing a job, you can also add a title to it. The title is visible at the top and bottom of the results page. For more details on how to prepare the query set to achieve the expected formatting on the results page, see [Prepare a Query Set](./prepare-a-query-set.mdx). Here's an example of a shared job results page: ### What Am I Sharing? You're sharing a view-only page with queries (or query labels if you added them to the query set) and answers from your files. When generating the link to the page, you can choose to allow viewers to browse sources. If you do that, they gain access to: - Documents the answer was based on (this includes titles and content). - Document metadata. ## Prerequisites A successfully completed job that ran across all files. ## Share a Job 1. In the navigation, go to **Jobs**. 2. Find the job you want to share and click **Share** next to it. 3. Configure the settings for the shared job: 1. Set the link expiration date. The page won't be available after this date. 2. Give your page a title. This title will be visible to the viewers. 3. Add any description to the job results. 4. Decide if you want to restrict access to the job to logged in users. If you enable this option, only users from your organization will be able to view the job results. They'll need to log in to do so. Otherwise, anyone with the link will have access to the results. 4. Generate and then copy the link. You can now share it with anyone you like. ## Stop Sharing a Job You can revoke access to a job at any time by simply deleting the link. To do this: 1. In the navigation, go to _Jobs_. 2. Find the job you want to stop sharing and click _Share_ next to it. 3. Click **Delete Link**. Once you delete the link, nobody can access the job results anymore. You must generate a new link to share them again. ## Download Job Results You can download job results as a CSV file directly from the job details page. Click the **Download** button to automatically start the download when the file is ready. --- ## Install the SDK There are two modes to install the SDK: the standard and the developer mode. Choose the standard mode lets you use methods already available in the package and the developer mode if you plan to modify it. *** ## Install in Standard Mode Install in this mode to use the methods already available in the package. Run the following command: ```shell pip install deepset-cloud-sdk ``` You can now use the CLI commands and Python methods included in the SDK. ## Install in Developer Mode Use this installation mode if you want to modify the package: 1. Clone [the GitHub repository](https://github.com/deepset-ai/deepset-cloud-sdk/tree/main). For help, see [GitHub docs](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). 2. Run the following command: ```shell pip install hatch==1.7.0 hatch build ``` ## Update the SDK Update the SDK to the newest version: ```shell pip install --upgrade deepset-cloud-sdk ``` ## Check the SDK Version Run the following command: ```shell deepset-cloud --version ``` ## Get Help Run: ```bash deepset-cloud --help ``` ```shell python3 -m deepset_cloud_sdk.cli --help ``` --- ## Download Files with Python You can download files from a workspace to a directory on your computer, including the files' metadata. Metadata are downloaded as separate JSON files with the `meta.json` suffix. *** ## Prerequisites ## Download Files Script Examples Here's a code to download files, including their metadata, to a local folder called `my_files`: ```python from deepset_cloud_sdk.workflows.sync_client.files import download download( api_key="", workspace_name="", file_dir=Path("./downloaded_files"), ) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import download async def my_async_context() -> None: await download( api_key="", workspace_name="", file_dir=Path("./downloaded_files"), ) ``` --- ## Get Upload Sessions Details Files are uploaded in an upload session. You can list all upload sessions or get a single session to check its status, creation time, and files uploaded. *** ## About This Task ### Sessions ## Prerequisites [Upload Files with Python](./upload-files-with-python.mdx). This creates a session. ## List All Sessions Script Examples Here's an example code you can use to list all active sessions: ```python from deepset_cloud_sdk.workflows.sync_client.files import list_upload_sessions for session_batch in list_upload_sessions( api_key="", workspace_name="", is_expired=False, # Set to True if you want to list expired sessions batch_size=100, # Adjust the batch size as needed ): for session in session_batch: # List of length 100 print(session.session_id) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import list_upload_sessions async def my_async_context() -> None: async for session_batch in list_upload_sessions( api_key="", workspace_name="", is_expired=False, # Set to True if you want to list expired sessions batch_size=100, # Adjust the batch size as needed ): for session in session_batch: # List of length 100 print(session.session_id) ``` ## Get Details of a Single Session Script Examples Here's the code you can use to view a single upload session. (You can get session IDs from the `list_upload_sessions()` method.) ```python from deepset_cloud_sdk.workflows.async_client.files import get_upload_session from uuid import UUID session_id = UUID( "enter-your-session-id-here" ) # Replace with your actual upload session ID returned by `list_upload_sessions` session_details = get_upload_session( api_key="", workspace_name="", session_id=session_id, ) print(session_details) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import get_upload_session from uuid import UUID session_id = UUID( "enter-your-session-id-here" ) # Replace with your actual upload session ID returned by `list_upload_sessions` async def my_async_context() -> None: session_details = await get_upload_session( api_key="", workspace_name="", session_id=session_id, ) print(session_details) ``` ## Close a Session You may need to close a session manually, for example, because you reached the limit of 10 open sessions to trigger file ingestion. You can do so using the [Close Session](/docs/api/main/close-session-api-v-1-workspaces-workspace-name-upload-sessions-session-id-put.api.mdx) REST API endpoint. You'll need the upload session ID, API key, and the name of the workspace where you're uploading the files. Copy this code, replacing the variables: ```curl curl --request PUT \ --url https://api.cloud.deepset.ai/api/v1/workspaces//upload_sessions/ \ --header 'accept: application/json' \ --header 'authorization: Bearer using the SDK. ## About This Task You can bring your Haystack pipeline or index into using an SDK method. You can specify the workspace where you want the pipeline or index to be imported. After being imported, you must deploy the pipeline or enable the index to be able to use it for search or file processing. You can import `Pipeline` and `AsyncPipeline`. For details, see [Haystack documentation](https://docs.haystack.deepset.ai/docs/asyncpipeline). The SDK uses the `Pipeline.dumps()` method under the hood to serialize the pipeline to YAML. :::info deepset and Haystack Pipelines There are some differences between and Haystack pipelines: - distinguishes between pipelines and indexes. - Pipelines and indexes take inputs and produce outputs. Make sure you understand how each of them works before importing. For more information, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Indexes](/docs/concepts/indexes/indexes.mdx). ::: ## Sync and Async Methods There are two clients available for import: `PipelineClient()`, which uses the synchronous import, and `AsyncPipelineClient()`, which uses asynchronous import. For usage examples, see the _Examples_ section below. ### Secrets You can import pipelines with environment variable-based secrets. Make sure you add the secrets to . You can do this either on the Integrations page, if it's an existing integration, or on the Secrets page. For details, see [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). Token-based secrets do not work in imported pipelines. ### Custom Components If the pipeline or index you're importing uses custom components, import them to first. For details, see [Working with Custom Components](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-a-custom-component.mdx). ### Document Stores For full indexing capabilities, such as detailed indexing status, use the core OpenSearchDocumentStore. If you're using another document store, check the instructions on how to connect to it: [Connect to an External Document Store](/docs/how-to-guides/working-with-your-data/connect-to-external-database.mdx). To understand how interacts with different document stores, check [Document Stores](/docs/concepts/document-stores/document-stores.mdx). ### Streaming The `streaming_callback` function is not serializable. Once you import your pipeline, you can enable streaming directly in Haystack Enterprise Platform. For details, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). ### Validation You can choose to validate the YAML of the pipeline or index you're importing by setting the `strict_validation` parameter of `PipelineConfig()` or `IndexConfig()` to `True`. The import fails if there are validation errors. By default, validation is set to `False`, which means validation errors are logged but the import continues. ### Output Type For pipelines, you can set the output type to properly display the answers it returns in Playground. For details, see [Set Pipeline Output Type](/docs/how-to-guides/designing-your-pipeline/set-additional-params/set-pipeline-output.mdx) and the Example section below. ## Prerequisites - You must understand pipelines and indexes and the concepts of inputs and outputs they take. For details, see [Indexes](/docs/concepts/indexes/indexes.mdx) and [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx). - You must have the latest version of Haystack installed. For details, see [Haystack documentation](https://docs.haystack.deepset.ai/docs/installation). - If the pipeline or index uses secrets, add them to . For more information, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx) and [Connect to Model and Service Providers](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx). - If the pipeline or index uses custom components, import them to . For details, see [Import Custom Components](/docs/api/main/import-custom-components-api-v-2-custom-components-post.api.mdx). - [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). - [Install](/docs/how-to-guides/working-with-the-sdk/install-the-sdk-1.mdx) and [configure the SDK](/docs/how-to-guides/working-with-the-sdk/using-the-command-line-interface-cli/set-up-the-sdk-cli.mdx): Install the latest version of the SDK and then use the `deepset-cloud login` command to pass the environment, API key, and workspace where you want to import your pipeline or index. You can also pass this configuration when initializing the SDK, but this is the preferred method. ## Import a Pipeline ### Using Sync Import When importing a pipeline with the synchronous method, use the `PipelineClient()`class. To define the pipeline's inputs and outputs, use the `PipelineConfig()` class. Here's the code you can use to import a Haystack pipeline: ```python from haystack import Pipeline # these components are used in the pipeline # make sure you import the components for your pipeline from haystack.components.builders import PromptBuilder from haystack.components.builders.answer_builder import AnswerBuilder from haystack.components.generators import OpenAIGenerator from haystack.utils import Secret from deepset_cloud_sdk import ( PipelineClient, PipelineConfig, PipelineInputs, PipelineOutputs, ) # Define the pipeline pipeline = Pipeline() # Add pipeline components prompt_builder = PromptBuilder(template="Answer this question: {{query}}", required_variables=["*"]) llm = OpenAIGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY", strict=False), model="gpt-4") answer_builder = AnswerBuilder() pipeline.add_component("prompt_builder", prompt_builder) pipeline.add_component("llm", llm) pipeline.add_component("answer_builder", answer_builder) pipeline.connect("prompt_builder.prompt", "llm.prompt") pipeline.connect("llm.replies", "answer_builder.replies") # Initialize the deepset SDK PipelineClient # Option 1 - Using environment variables (recommended): # This assumes you've run `deepset-cloud login` to set up environment variables in your .env file client = PipelineClient() # Option 2 - Using explicit parameters: # Alternatively, you can pass api_key, workspace_name, and api_url explicitly # client = PipelineClient( # api_key="your-api-key", # workspace_name="your-workspace", # api_url="https://api.cloud.deepset.ai/api/v1" # ) # Configure the pipeline import config = PipelineConfig( name="my-pipeline", # Name for your pipeline in Haystack Enterprise Platform inputs=PipelineInputs( query=["prompt_builder.query"] # List the components and their inputs that should receive the query ), outputs=PipelineOutputs( answers="answer_builder.answers" # List the components and their output names that return answers ), strict_validation=True, # Fails the import if the pipeline YAML fails validation, by default set to `False` overwrite=True, # Overwrites a pipeline with the same name that already exists in deepset ) # Import the pipeline client.import_into_deepset(pipeline, config) ``` ### Using Async Import This example uses the async import method with `AsyncPipelineClient()`: ```python from haystack import Pipeline # these components are used in the pipeline # make sure you import the components for your pipeline from haystack.components.builders import PromptBuilder from haystack.components.builders.answer_builder import AnswerBuilder from haystack.components.generators import OpenAIGenerator from haystack.utils import Secret from deepset_cloud_sdk import ( AsyncPipelineClient, PipelineConfig, PipelineInputs, PipelineOutputs, ) async def main(): # Define the pipeline pipeline = Pipeline() # Add pipeline components prompt_builder = PromptBuilder(template="Answer this question: {{query}}", required_variables=["*"]) llm = OpenAIGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY", strict=False), model="gpt-4") answer_builder = AnswerBuilder() pipeline.add_component("prompt_builder", prompt_builder) pipeline.add_component("llm", llm) pipeline.add_component("answer_builder", answer_builder) pipeline.connect("prompt_builder.prompt", "llm.prompt") pipeline.connect("llm.replies", "answer_builder.replies") # Initialize the deepset SDK AsyncPipelineClient # Option 1 - Using environment variables (recommended): # This assumes you've run `deepset-cloud login` to set up environment variables in your .env file client = AsyncPipelineClient() # Option 2 - Using explicit parameters: # Alternatively, you can pass api_key, workspace_name, and api_url explicitly # client = AsyncPipelineClient( # api_key="your-api-key", # workspace_name="your-workspace", # api_url="https://api.cloud.deepset.ai/api/v1" # ) # Configure the pipeline import config = PipelineConfig( name="my-pipeline-async", # Name for your pipeline in Haystack Enterprise Platform inputs=PipelineInputs( query=["prompt_builder.query"] # List the components and their inputs that should receive the query ), outputs=PipelineOutputs( answers="answer_builder.answers" # List the components and their output names that return answers ), strict_validation=True, # Fails the import if the pipeline YAML fails validation, by default set to `False` overwrite=True, # Overwrites a pipeline with the same name that already exists in deepset ) # Import the pipeline await client.import_into_deepset(pipeline, config) asyncio.run(main()) ``` ## Import an Index ### Using Sync Import When importing an index with the sync method, initialize the `PipelineClient()` method and then use the `IndexConfig()` class to define the index inputs. Here's the code you can use to import an index: ```python from haystack import Pipeline from haystack.components.converters.txt import TextFileToDocument # import all the components your index is using, for example: from haystack.components.routers.file_type_router import FileTypeRouter from haystack.components.writers import DocumentWriter from haystack_integrations.document_stores.opensearch.document_store import ( OpenSearchDocumentStore, ) from deepset_cloud_sdk import IndexConfig, IndexInputs, PipelineClient # Configure your index index = Pipeline() # Initialize index components, for example: file_classifier = FileTypeRouter(mime_types=[ "text/plain" ]) text_converter = TextFileToDocument(encoding="utf-8") # Add components to the index, for example: index.add_component("file_classifier", file_classifier) index.add_component("super_text_converter", text_converter) index.add_component( "writer", DocumentWriter( OpenSearchDocumentStore( index="", max_chunk_bytes=104857600, embedding_dim=768, return_embedding=False, create_index=True ) ) ) # Connect the components index.connect("file_classifier.text/plain", "super_text_converter.sources") index.connect("super_text_converter.documents", "writer.documents") # Initialize the deepset SDK PipelineClient() # Option 1 - Using environment variables (recommended): # This assumes you've run `deepset-cloud login` to set up environment variables in your .env file client = PipelineClient() # Option 2 - Using explicit parameters: # Alternatively, you can pass api_key, workspace_name, and api_url explicitly # client = PipelineClient( # api_key="your-api-key", # workspace_name="your-workspace", # api_url="https://api.cloud.deepset.ai/api/v1" # ) # Configure the import config = IndexConfig( name="my-index", # specify the name under which the index will appear in deepset inputs=IndexInputs(files=["file_classifier.sources"]), # define the components and their input names that should receive files strict_validation=False, #this logs YAML validation errors but doesn't fail the import overwrite=True, # overwrites an index with the same name that already exists in deepset ) # Import the index client.import_into_deepset(index, config) ``` ### Using Async Import Use the `AsyncPipelineClient()` to import async. This code shows you how to do this: ```python from haystack import Pipeline from haystack.components.converters.txt import TextFileToDocument # import all the components your index is using, for example: from haystack.components.routers.file_type_router import FileTypeRouter from haystack.components.writers import DocumentWriter from haystack_integrations.document_stores.opensearch.document_store import ( OpenSearchDocumentStore, ) from deepset_cloud_sdk import IndexConfig, IndexInputs, AsyncPipelineClient async def main(): # Configure your index index = Pipeline() # Initialize index components, for example: file_classifier = FileTypeRouter(mime_types=[ "text/plain" ]) text_converter = TextFileToDocument(encoding="utf-8") # Add components to the index, for example: index.add_component("file_classifier", file_classifier) index.add_component("super_text_converter", text_converter) index.add_component( "writer", DocumentWriter( OpenSearchDocumentStore( index="", max_chunk_bytes=104857600, embedding_dim=768, return_embedding=False, create_index=True ) ) ) # Connect the components index.connect("file_classifier.text/plain", "super_text_converter.sources") index.connect("super_text_converter.documents", "writer.documents") # Initialize the deepset SDK AsyncPipelineClient() # Option 1 - Using environment variables (recommended): # This assumes you've run `deepset-cloud login` to set up environment variables in your .env file client = AsyncPipelineClient() # Option 2 - Using explicit parameters: # Alternatively, you can pass api_key, workspace_name, and api_url explicitly # client = AsyncPipelineClient( # api_key="your-api-key", # workspace_name="your-workspace", # api_url="https://api.cloud.deepset.ai/api/v1" # ) # Configure the import config = IndexConfig( name="my-index-4", # specify the name under which the index will appear in deepset inputs=IndexInputs(files=["file_classifier.sources"]), # define the components and their input names that should receive files strict_validation=False, #this logs YAML validation errors but doesn't fail the import overwrite=True, # overwrites an index with the same name that already exists in deepset ) # Import the index await client.import_into_deepset(index, config) asyncio.run(main()) ``` ## Examples ### Index This is an example of how to import an index with the sync import into : ```python from haystack import Pipeline from haystack.components.routers.file_type_router import FileTypeRouter from haystack.components.converters.txt import TextFileToDocument from haystack.components.converters.pdfminer import PDFMinerToDocument from haystack.components.converters.html import HTMLToDocument from haystack.components.converters.docx import DOCXToDocument from haystack.components.converters.pptx import PPTXToDocument from haystack.components.converters.xlsx import XLSXToDocument from haystack.components.converters.csv import CSVToDocument from haystack.components.joiners.document_joiner import DocumentJoiner from haystack.components.preprocessors.document_splitter import DocumentSplitter from haystack.components.embedders.sentence_transformers_document_embedder import SentenceTransformersDocumentEmbedder from haystack_integrations.document_stores.opensearch.document_store import OpenSearchDocumentStore from haystack.components.writers.document_writer import DocumentWriter from deepset_cloud_sdk import PipelineClient, IndexConfig, IndexInputs from haystack.document_stores.types import DuplicatePolicy # Explicitly call the function to add the publish method pipeline_client = PipelineClient( workspace_name="new", api_key="api_key", api_url="https://api.cloud.deepset.ai/api/v1" ) # Initialize components file_classifier = FileTypeRouter(mime_types=[ "text/plain", "application/pdf", "text/markdown", "text/html", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "text/csv" ]) text_converter = TextFileToDocument(encoding="utf-8") pdf_converter = PDFMinerToDocument( line_overlap=0.5, char_margin=2, line_margin=0.5, word_margin=0.1, boxes_flow=0.5, detect_vertical=True, all_texts=False, store_full_path=False ) markdown_converter = TextFileToDocument(encoding="utf-8") html_converter = HTMLToDocument( extraction_kwargs={ "output_format": "markdown", "target_language": None, "include_tables": True, "include_links": True } ) docx_converter = DOCXToDocument(link_format="markdown") pptx_converter = PPTXToDocument() xlsx_converter = XLSXToDocument() csv_converter = CSVToDocument(encoding="utf-8") joiner = DocumentJoiner(join_mode="concatenate", sort_by_score=False) joiner_xlsx = DocumentJoiner(join_mode="concatenate", sort_by_score=False) splitter = DocumentSplitter( split_by="word", split_length=250, split_overlap=30, respect_sentence_boundary=True, language="en" ) document_embedder = SentenceTransformersDocumentEmbedder( normalize_embeddings=True, model="intfloat/e5-base-v2" ) opensearchdocumentstore = OpenSearchDocumentStore( index="default", max_chunk_bytes=104857600, embedding_dim=768, return_embedding=False, create_index=True ) writer = DocumentWriter(document_store=opensearchdocumentstore, policy=DuplicatePolicy.OVERWRITE) # Create and configure pipeline pipeline_index = Pipeline() # Add components pipeline_index.add_component("file_classifier", file_classifier) pipeline_index.add_component("text_converter", text_converter) pipeline_index.add_component("pdf_converter", pdf_converter) pipeline_index.add_component("markdown_converter", markdown_converter) pipeline_index.add_component("html_converter", html_converter) pipeline_index.add_component("docx_converter", docx_converter) pipeline_index.add_component("pptx_converter", pptx_converter) pipeline_index.add_component("xlsx_converter", xlsx_converter) pipeline_index.add_component("csv_converter", csv_converter) pipeline_index.add_component("joiner", joiner) pipeline_index.add_component("joiner_xlsx", joiner_xlsx) pipeline_index.add_component("splitter", splitter) pipeline_index.add_component("document_embedder", document_embedder) pipeline_index.add_component("writer", writer) # Connect components pipeline_index.connect("file_classifier.text/plain", "text_converter.sources") pipeline_index.connect("file_classifier.application/pdf", "pdf_converter.sources") pipeline_index.connect("file_classifier.text/markdown", "markdown_converter.sources") pipeline_index.connect("file_classifier.text/html", "html_converter.sources") pipeline_index.connect("file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx_converter.sources") pipeline_index.connect("file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx_converter.sources") pipeline_index.connect("file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx_converter.sources") pipeline_index.connect("file_classifier.text/csv", "csv_converter.sources") pipeline_index.connect("text_converter.documents", "joiner.documents") pipeline_index.connect("pdf_converter.documents", "joiner.documents") pipeline_index.connect("markdown_converter.documents", "joiner.documents") pipeline_index.connect("html_converter.documents", "joiner.documents") pipeline_index.connect("docx_converter.documents", "joiner.documents") pipeline_index.connect("pptx_converter.documents", "joiner.documents") pipeline_index.connect("joiner.documents", "splitter.documents") pipeline_index.connect("splitter.documents", "joiner_xlsx.documents") pipeline_index.connect("xlsx_converter.documents", "joiner_xlsx.documents") pipeline_index.connect("csv_converter.documents", "joiner_xlsx.documents") pipeline_index.connect("joiner_xlsx.documents", "document_embedder.documents") pipeline_index.connect("document_embedder.documents", "writer.documents") index_config = IndexConfig( name="demo0", inputs=IndexInputs( files=["file_classifier.sources"], ), ) if __name__ == "__main__": pipeline_client.import_into_deepset(pipeline=pipeline_index, config=index_config) # asyncio.run(pipeline_client.import_into_deepset_async(pipeline=pipeline_index, config=index_config)) print(f"index {index_config.name} published") ``` ### With Validation Enabled Setting `strict_validation=True` fails the import if there are issues with the pipeline YAML. Here's how to enable validation: ```python from deepset_cloud_sdk import DeepsetValidationError, PipelineClient, PipelineConfig, PipelineInputs, PipelineOutputs ... # Here you'd define the pipeline components and connect them # Enable validation when configuring the import config = PipelineConfig( name="my-simple-pipeline-validated", # Name for your pipeline in Haystack Enterprise Platform inputs=PipelineInputs( query=["prompt_builder.query"] # Which component parameter receives the query ), outputs=PipelineOutputs( answers="answer_builder.answers" # Which component output provides the answers ), strict_validation=True # prevents import on validation errors ) # When importing the pipeline, you may catch validation errors using DeepsetValidationError try: client.import_into_deepset(pipeline, config) except DeepsetValidationError as err: # Manage validation errors print(err) ... ``` ### Overwriting Existing Pipelines with the Same Name You can choose to overwrite pipelines that already exist in deepset and have the same name as the pipeline you're importing. Use the `overwrite` setting to do that: ```python config = PipelineConfig( name="my-pipeline", # Name for your pipeline in Haystack Enterprise Platform inputs=PipelineInputs( query=["prompt_builder.query"] # Which component parameter receives the query ), outputs=PipelineOutputs( answers="answer_builder.answers" # Which component output provides the answers ), overwrite=True # set to True to overwrite the pipeline if it already exists ) ``` ### With Output Type Set To set the pipeline output type, import `PipelineOutputType` and set it to one of the options: `generative`, `chat`, `extractive`, or `document`. This example sets the pipeline type to `chat`: ```python from deepset_cloud_sdk import PipelineClient, PipelineConfig, PipelineInputs, PipelineOutputs, PipelineOutputType config = PipelineConfig( name="my-simple-pipeline-output-type", # Name for your pipeline in Haystack Enterprise Platform inputs=PipelineInputs( query=["prompt_builder.query"] # Which component parameter receives the query ), outputs=PipelineOutputs( answers="llm.replies" # Which component output provides the answers ), pipeline_output_type=PipelineOutputType.CHAT # set pipeline_output_type here ) ``` ## What To Do Next - Check if you want to swap any of your pipeline components for deepset-specific components. For example. `DeepsetAnswerBuilder` can format and output references in a way `AnswerBuilder` can't. - Make sure the pipeline or index works. Fix any errors that you may see in the Builder. - If you imported a pipeline, you must deploy it to use it for search. For details, see [Deploy a Pipeline](/docs/how-to-guides/designing-your-pipeline/deploy-a-pipeline.mdx). - If you imported an index, you must enable it to process the files. For details, see [Enable an Index](/docs/how-to-guides/working-with-indexes/enable-an-index.mdx). --- ## List Existing Files with Python You can list all the files that exist in a workspace. *** # Prerequisites ## List Files Script Examples ### List All Files in a Workspace Here's a basic script example you can use to list all files in a workspace: ```python from deepset_cloud_sdk.workflows.sync_client.files import list_files for file_batch in list_files( api_key="", workspace_name="", batch_size=10, ): for file in file_batch: # Lists with length 10 of files print(file.name) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import list_files async def my_async_context() -> None: async for file_batch in list_files( api_key="", workspace_name="", batch_size=10, ): for file in file_batch: print(file.name) ``` ### List Files by Name Here's an example of how to use the `list_files()` method to list files in a workspace by their name: ```python from deepset_cloud_sdk.workflows.sync_client.files import list_files for file_batch in list_files( api_key="", workspace_name="", name="specific_filename.txt" # Uses fuzzy search for file names batch_size=10, ): for file in file_batch: print(file.name) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import list_files async def my_async_context() -> None: async for file_batch in list_files( api_key="", workspace_name="", name="specific_filename.txt" # Uses fuzzy search for file names ): for file in file_batch: print(file.name) ``` ### List Files by Filter This example uses an OData filter to list files in a workspace: ```python from deepset_cloud_sdk.workflows.sync_client.files import list_files for file_batch in list_files( api_key="", workspace_name="", odata_filter="modified gt 2023-01-01T00:00:00Z" ): for file in file_batch: print(file.name) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import list_files async def my_async_context() -> None: async for file_batch in list_files( api_key="", workspace_name="", odata_filter="modified gt 2023-01-01T00:00:00Z" ): for file in file_batch: print(file.name) ``` --- ## Upload Files with Python Use this method if you have many files to upload or want to upload files with metadata. *** ## About This Task Uploading files using the Python methods included in the SDK is asynchronous and uses sessions under the hood. It's best for uploading large numbers of files with metadata. To upload files using this method, create and run a Python script. You can find example scripts at the bottom of this page. To learn more, see also [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx) and [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx). ### Sessions ### Folder Structure ### File Extensions ## Prerequisites ## Upload Scripts Examples ### Upload From a Folder Here is an example of a synchronous and asynchronous way to upload files from a folder. **Note**: When using Jupyter Notebooks, use this import before loading the SDK: ```python nest_asyncio.apply() from deepset_cloud_sdk.workflows.sync_client.files import list_files # you can install it with pip install nest-asyncio ``` Switch between the tabs to check the sync and async example: ```python from pathlib import Path from deepset_cloud_sdk.workflows.sync_client.files import upload # Uploads all files from a given path upload( paths=[Path("")], api_key="", workspace_name="", blocking=True, # waits until the files are displayed in deepset, # this may take a couple of minutes timeout_s=300, # the timeout for the `blocking` parameter in number of seconds show_progress=True, # shows the progress bar recursive=True, # uploads files from all subfolders as well ) ``` ```python from pathlib import Path from deepset_cloud_sdk.workflows.async_client.files import upload # Uploads all files from a given path. async def my_async_context() -> None: await upload( paths=[Path("")], api_key="", workspace_name="", blocking=True, # waits until the files are displayed in deepset Cloud, # this may take a couple of minutes timeout_s=300, # the timeout for the `blocking` parameter in number of seconds show_progress=True, # shows the progress bar recursive=True, # uploads files from all subfolders as well ) # Run the async function if __name__ == "__main__": asyncio.run(my_async_context()) ``` ### Upload Bytes You can upload files as bytes to a workspace. This method is suitable for all file types. Here are examples of a synchronous and an asynchronous way to do this: ```python from deepset_cloud_sdk.workflows.sync_client.files import upload_bytes, DeepsetCloudFileBytes upload_bytes( api_key="", workspace_name="", # optional, by default the environment variable "DEFAULT_WORKSPACE_NAME" is used files=[ DeepsetCloudFileBytes( name="example.txt", file_bytes=b"this is text", meta={"key": "value"}, # optional ) ], blocking=True, # optional, by default True timeout_s=300, # optional, by default 300 ) ``` ```python from deepset_cloud_sdk.workflows.async_client.files import upload_bytes, DeepsetCloudFileBytes async def my_async_context() -> None: await upload_bytes( api_key="", workspace_name="", # optional, by default the environment variable "DEFAULT_WORKSPACE_NAME" is used files=[ DeepsetCloudFileBytes( name="example.txt", file_bytes=b"this is some byte text", meta={"key": "value"}, # optional ) ], blocking=True, # optional, by default True timeout_s=300, # optional, by default 300 ) # Run the async function if __name__ == "__main__": asyncio.run(my_async_context()) ``` ### Synchronize GitHub Files with Here's an example script to load TXT and MD files from GitHub and send them to . It fetches the content as texts from GitHub and forwards them to . ```python from typing import List from urllib.parse import urlparse from deepset_cloud_sdk.workflows.sync_client.files import upload_texts, WriteMode, DeepsetCloudFile # Place your API key here API_KEY: str = "" def _parse_filename(url: str) -> str: """Parses the filename from a URL. :param url: URL to parse the filename from :return: Filename """ path = urlparse(url).path filename = path.split("/")[-1] return filename def fetch_and_prepare_files(urls: List[str]) -> List[DeepsetCloudFile]: """Fetches files from URLs and converts them to DeepsetCloudFile objects. These Objects can be uploaded to the Haystack Enterprise Platform directly without having to first copy them to disk. :param urls: List of URLs to fetch files from :return: List of DeepsetCloudFile objects """ files_to_upload: List[DeepsetCloudFile] = [] for url in urls: response = httpx.get(url) response.raise_for_status() file = DeepsetCloudFile( text=response.text, name=_parse_filename(url), meta={"url": url}, ) files_to_upload.append(file) return files_to_upload # URLs of files to download and upload DOWNLOAD_URLS: List[str] = [ "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example.txt", "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example2.txt", "https://raw.githubusercontent.com/deepset-ai/haystack/main/README.md", ] files = fetch_and_prepare_files(DOWNLOAD_URLS) # Upload .txt and .md files to deepset Cloud upload_texts( workspace_name="upload-test-123", # optional, uses "DEFAULT_WORKSPACE_NAME" by default files=files, blocking=False, # Set to False for non-blocking uploads timeout_s=300, # Optional, default is 300 seconds show_progress=True, # Optional, default is True api_key=API_KEY, write_mode=WriteMode.OVERWRITE, ) ``` ### Download Files from a URL and Upload to #### Using Threading This script downloads TXT and MD files from the URL you specify and then uploads them to using threading. Note that the maximum concurrency (processes in `multiprocessing.pool(processes=3)` ) is limited by the amount of cores in your system. For maximum utilization, you can use `multiprocessing.cpu_count()` to set the number of processes. ```python from typing import List from urllib.parse import urlparse from deepset_cloud_sdk.workflows.sync_client.files import upload_texts, WriteMode, DeepsetCloudFile # Place your API key and workspace name here API_KEY: str = "" WORKSPACE: str = "" def _parse_filename(url: str) -> str: """Parses the filename from a URL. :param url: URL to parse the filename from :return: Filename """ path = urlparse(url).path filename = path.split("/")[-1] return filename def fetch_and_upload_file(url: str) -> None: """Fetches a file from the given URL and converts it to a DeepsetCloudFile object. That Object can be uploaded to the Haystack Enterprise Platform directly without having to first copy them to disk. :param url: URL to fetch files from """ response = httpx.get(url) response.raise_for_status() file = DeepsetCloudFile( text=response.text, name=_parse_filename(url), meta={"url": url}, ) upload_texts( workspace_name=WORKSPACE, # optional, uses "DEFAULT_WORKSPACE_NAME" by default files=[file], blocking=False, # Set to False for non-blocking uploads timeout_s=300, # Optional, default is 300 seconds show_progress=True, # Optional, default is True api_key=API_KEY, write_mode=WriteMode.OVERWRITE, ) # URLs of files to download and upload DOWNLOAD_URLS: List[str] = [ "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example.txt", "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example2.txt", "https://raw.githubusercontent.com/deepset-ai/haystack/main/README.md", ] if __name__ == '__main__': # Upload .txt and .md files to deepset Cloud # Start one thread per URL to download and upload the files with multiprocessing.Pool(processes=3) as pool: results = pool.map(fetch_and_upload_file, DOWNLOAD_URLS) ``` #### Async This example downloads files from a URL you specify and then uploads them asynchronously to : ```python from typing import List from urllib.parse import urlparse from deepset_cloud_sdk.workflows.sync_client.files import WriteMode, DeepsetCloudFile from deepset_cloud_sdk.workflows.async_client.files import upload_texts # Place your API key and workspace name here API_KEY: str = "" WORKSPACE: str = "" def _parse_filename(url: str) -> str: """Parses the filename from a URL. :param url: URL to parse the filename from :return: Filename """ path = urlparse(url).path filename = path.split("/")[-1] return filename async def fetch_and_upload_file(url: str) -> None: """Fetches a file from the given URL and converts it to a DeepsetCloudFile object. That Object can be uploaded to the Haystack Enterprise Platform directly without having to first copy them to disk. :param url: URL to fetch file from """ async with httpx.AsyncClient() as client: response = await client.get(url) response.raise_for_status() file = DeepsetCloudFile( text=response.text, name=_parse_filename(url), meta={"url": url}, ) await upload_texts( workspace_name=WORKSPACE, # optional, uses "DEFAULT_WORKSPACE_NAME" environment variable by default files=[file], blocking=False, # Set to False for non-blocking uploads timeout_s=300, # Optional, default is 300 seconds show_progress=True, # Optional, default is True api_key=API_KEY, write_mode=WriteMode.OVERWRITE, ) async def main(urls: List[str]) -> None: """Main function to run the asynchronous fetching and uploading of files.""" tasks = [fetch_and_upload_file(url) for url in urls] await asyncio.gather(*tasks) # URLs of files to download and upload DOWNLOAD_URLS: List[str] = [ "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example.txt", "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example2.txt", "https://raw.githubusercontent.com/deepset-ai/haystack/main/README.md", ] # Run the main function if __name__ == "__main__": asyncio.run(main(DOWNLOAD_URLS)) ``` #### From Memory in Byte Format Here's an example of how to fetch a PDF file from a given URL, convert it to a byte format, and then upload it to : ```python from typing import List from urllib.parse import urlparse from deepset_cloud_sdk.workflows.sync_client.files import ( DeepsetCloudFileBytes, WriteMode, upload_bytes, ) # Place your API key and workspace name here API_KEY: str = "" WORKSPACE: str = "" def _parse_filename(url: str) -> str: """Parses the filename from a URL. :param url: URL to parse the filename from :return: Filename """ path = urlparse(url).path filename = path.split("/")[-1] return filename def fetch_and_upload_file(url: str) -> None: """Fetches a file from the given URL and converts it to a DeepsetCloudFile object. That Object can be uploaded to the Haystack Enterprise Platform directly without having to first copy them to disk. :param url: URL to fetch files from """ response = httpx.get(url) response.raise_for_status() file = DeepsetCloudFileBytes( file_bytes=response.content, name=_parse_filename(url), meta={"url": url}, ) upload_bytes( workspace_name=WORKSPACE, # optional, by default the environment variable "DEFAULT_WORKSPACE_NAME" is used files=[file], # by default blocking=True - by setting to False it will mean that you can immediately # continue uploading another batch of files blocking=False, timeout_s=300, # optional, by default 300 show_progress=True, # optional, by default True api_key=API_KEY, write_mode=WriteMode.OVERWRITE, ) # URLs of files to download and upload DOWNLOAD_URLS: List[str] = [ "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example.txt", "https://raw.githubusercontent.com/deepset-ai/deepset-cloud-sdk/main/test-upload/example2.txt", "https://raw.githubusercontent.com/deepset-ai/haystack/main/README.md", "https://sherlock-holm.es/stories/pdf/letter/1-sided/advs.pdf", ] if __name__ == '__main__': # Upload .txt and .pdf files to deepset Cloud # Start one thread per URL to download and upload the files with multiprocessing.Pool(processes=4) as pool: results = pool.map(fetch_and_upload_file, DOWNLOAD_URLS) ``` ### Google Colab Notebook Here's a Colab notebook with different upload scenarios you can test: [Upload files with SDK in Google Colab](https://colab.research.google.com/drive/1y2KMB606h-57BafCkhuiaXFWo4gDKtG3). --- ## Using Python Methods Make use of the Python methods included in the SDK. Learn about synchronous and asynchronous client and when to use each. *** :::tip Configuring Workspace and API Key When using Python methods, you can first configure the API key and default workspace for all operations using the CLI. You won't need to pass this information in your scripts if you do that. ::: ## Synchronous and Asynchronous Client SDK includes a synchronous and an asynchronous client. The synchronous client blocks execution until it receives a response from the server. This means the code pauses after sending a request and waits for the server's reply before continuing. This approach is easier to understand and debug because it follows a straightforward, linear execution path. However, it may not be the most resource-efficient method if your application needs to manage multiple tasks at the same time, particularly in operations that are bound by input/output limitations. The asynchronous client allows the code to run continuously while waiting for the server's response. This functionality is enabled by Python's asyncio library, which supports executing multiple operations concurrently. Instead of pausing to wait for one operation to finish before starting the next, this method handles several tasks simultaneously. It's particularly useful for I/O-bound tasks like network requests. ### Running the Asynchronous Client To run asynchronous code, you typically define functions with `async def` and use `await` to call them. For example: ```python from deepset_cloud_sdk.workflows.async_client.files import list_files async def my_async_context() -> None: async for file_batch in list_files( api_key="", workspace_name="", api_url="", batch_size=10, ): for file in file_batch: print(file.name) # Run the async function if __name__ == "__main__": asyncio.run(my_async_context()) --- ## List Existing Files with CLI Print a list of files that exist in the workspace you specify. The list includes the file name and ID, URL, size, creation timestamp, and metadata. *** ## Prerequisites ## List Files 1. Pass your API key and the name of the workspace whose files you want to list. (You can also skip this step and just pass your API key and workspace in the `list-files` command.) ```shell # This command prompts you to pass the deepset API key and workspace name deepset-cloud login ``` 2. Run the following command to get a list of the files in the workspace you specified: ```shell deepset-cloud list-files ``` A table with file details is displayed in the console. ## Examples This command lists all files whose names contain the string `hilton_hotel` that exist in the "hotels" workspace. The list is broken up into batches of 20 files. It also includes the API key to connect to : ```shell deepset-cloud list-files --api-key --workspace-name hotels --name "hilton-hotel" --batch-size 20 ``` --- ## Download Files with CLI Using the SDK command-line interface, you can download files from a workspace to your local machine. *** ## Prerequisites ## Download Files 1. Pass your API key and the name of the workspace where you want to upload the files. (You can also skip this step and just pass your API key and workspace in the `download` command.) ```shell # This command prompts you to pass the deepset API key and workspace name deepset-cloud login ``` 2. Run the following command to download the files. This command downloads all files from the workspace to a folder you specify: ```shell deepset-cloud download --file-dir ``` The files are downloaded to the folder you specified, including all metadata. Metadata are downloaded as separate JSON files with the `meta.json` suffix. ## Examples - This command uses an odata filter to narrow down the files downloaded. In this case, it downloads files with the following metadata: `{"Hotel_Address": "Amsterdam Netherlands"}` to the `hotels` directory: ```shell deepset-cloud download --file-dir "./hotels" --odata-filter "Hotel_Address eq 'Amsterdam Netherlands'" ``` - This command downloads files whose names contain the string `westcord_art_hotel_amsterdam_4_stars` from the "hotels" workspace. It also includes the API key to connect to : ```shell deepset-cloud download --file-dir "./hotels" --api-key --workspace-name hotels --name "westcord_art_hotel_amsterdam_4_stars" ``` - This command downloads files to the current directory without their metadata: ```shell deepset-cloud download ---no-include-meta ``` --- ## Set Up the SDK CLI # Set Up the Command Line interface SDK comes with a command-line interface (CLI) that's fast and easy to use. Before you start working with the SDK through command-line, set the API key for accessing and the default workspace for all operations. *** ## Prerequisites 3. Run the following command to ensure you have the latest version of the SDK installed: ```python deepset-cloud --version ``` ## Log In 1. Run the following command: ```python deepset-cloud login ``` 2. Choose the environment: 1. `eu` (default): For deployments in Europe, sets the environment to `https://api.cloud.deepset.ai/`. 2. `us`: For deployments in the US, sets the environment to: `https://api.us.deepset.ai/`. 3. `custom`: For on-premise deployments, you must provide the API URL. 3. When prompted, paste your API key. 4. Type the name of the workspace you want to set as default for all operations. Running the `login` command creates an .ENV file `~/.deepset-cloud/.env` containing your API key and default workspace. The SDK uses this file as the default configuration for all subsequent CLI commands. ## Getting Help Use `--help` to see available commands: ```python deepset-cloud --help ``` ## Log Out To delete the .ENV file with your credentials, run: ```python deepset-cloud logout ``` ## Check the SDK Version To verify if you have the latest SDK version installed, run: ```shell deepset-cloud --version ``` --- ## Upload Files with CLI Upload files and folders, including metadata, through the command-line. *** ## About This Task Uploading through CLI is asynchronous. It's the recommended method if you have a lot of files to upload or want to upload files with metadata. To learn more, see also [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx) and [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx). ### Sessions ### Folder Structure ### File Extensions ## Prerequisites ## Upload Files 1. Pass your API key and the name of the workspace where you want to upload the files. (You can also skip this step and just pass your API key and workspace in the `update` command.) ```python # This command prompts you to pass the deepset API key and workspace name deepset-cloud login ``` 2. Run the following command to upload your files, specifying any options you want: ```python deepset-cloud upload ``` While the upload is progressing, you can first see the upload status, which means the files were uploaded to the S3 bucket, and then the ingestion status, which means the files are being transferred to . Both processes must be successful for the files to be uploaded to . ## Examples - Upload all TXT and PDF files from the folder, including subfolders, and overwrite any duplicate files: ```python deepset-cloud upload ./hotel_reviews --recursive --write-mode OVERWRITE ``` - Upload Markdown files passing the workspace name and API key: ```python deepset-cloud upload ./hotel_reviews --api-key api_123 --workspace-name my_workspace ``` - Upload only JSON files from a collection of multiple file types: ```python deepset-cloud upload ./hotel_reviews --api-key api_123 --workspace-name my_workspace --use-type .json ``` --- ## Working with the SDK # Getting Started with the SDK The open [source SDK package](https://github.com/deepset-ai/deepset-cloud-sdk/tree/main) is available on GitHub, and provides methods for uploading and listing files. It offers a command-line interface (CLI) that's fast and easy to use, as well as Python methods. It's best suited for efficiently uploading large numbers of files with metadata. We're actively maintaining this SDK, and enhancing it with new methods. --- ## Connect to an External Document Store Run your query pipelines on data stored in an external database, such as Pinecone, Weaviate, Qdrant, or others. *** ## About this Task These databases act as document stores in . For more information, see [Document Stores](/docs/concepts/document-stores/document-stores.mdx). You can also add an integration with any other database through a custom component. For details, see [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx). ## Prerequisites - You need an active API key to the database you want to use. - Basic knowledge of document stores in . For details, see [Document Stores](docs/concepts/document-stores/document-stores.mdx). - Understanding of secrets in . For more information, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). - Check the parameters you can configure for your document store, especially the name of the parameter for passing the API key. See the documentation for your document store in the [Document Stores](docs/concepts/document-stores/document-stores.mdx) section. ## Run Queries on Data in Your Document Store This task involves three steps: 1. Create a secret to securely store your API key to the document store. 2. Write your documents to the document store. 3. Retrieve documents from the document store. ### Create a Secret for Your Document Store :::info MongoDB To use `MongoDBAtlasDocumentStore`, you can simply paste your API key on the Integrations page: 1. Click your profile icon in the top right corner and choose **Connections**. 2. Find MongoDB, click **Connect**, and paste the API key. ::: This step is needed to enable a connection with the database you want to use as the document store without adding the API key explicitly in the configuration. You can add a secret only for a single workspace or for the whole organization: You'll then use the secret name as the API key for components that need to connect to the document store. ### Write Documents into the Document Store `DocumentWriter` is the component that writes preprocessed documents into the document store. You must add it at the end of your index. 1. Build your index and add `DocumentWriter` as its last component. For help, see [Create an Index](/docs/how-to-guides/working-with-indexes/create-an-index.mdx). :::info Index from a template If you're' using a template, `DocumentWriter` is already there connected to an `OpenSearchDocumentStore`. You can delete the document store and replace it with another one. ::: 2. In Builder, click **Add** and search for "document store". You get a list of all available document stores. Choose a the one you want to use and drag it onto the canvas. 3. Connect the document store to `DocumentWriter`. 4. Click the document store card and configure it. 5. Save your index. ### Retrieve Documents From the Document Store Each document store has dedicated retrievers that are called the same as the document store. For example, `MongoDBAtlasDocumentStore` has two compatible retrievers: `MongoDBAtlasEmbeddingRetriever` and `MongoDBAtlasFullTextRetriever`. Add the retrievers to your query pipeline and configure the document store they should connect to in the same way you configured `DocumentWriter`. Pass the secret's name as the API key for the document store. --- ## Connect Your OpenSearch Cluster You can store the files in your AWS OpenSearch cluster and connect to it. This way, you control where your files are stored but you can still use them in your search app. *** ## About This Task Currently, we support connecting Amazon Web Services OpenSearch clusters in the `eu-central-1` region to . When you connect to your OpenSearch cluster, here's how it works: First, you upload your data to . Then, takes care of seamlessly transferring your data to the OpenSearch cluster. Although you can still view the files in , they're located in your OpenSearch cluster. You can use one or two AWS clusters for this. We recommend you use two OpenSearch clusters: one for the workspace files and one for serving the pipelines. This way, you can save money, as the workspace cluster doesn't need that many resources. The workspace cluster is where the files are stored as raw text. It's not used for search, and it doesn't store the vector representations of the files. For this cluster, you need a basic setup and less memory than for the pipeline cluster. The pipeline cluster is the cluster where vector representations of files are stored and where the search happens. This cluster needs more memory than the workspace cluster. When you allocate memory to it, also consider whether you're planning to run a vector-based or keyword-based search on the files stored in this cluster. Vector-based search needs more memory than keyword-based one. You can connect to your Amazon OpenSearch Services cluster through API. There are four steps to do that: 1. Authorize the AWS account to connect to your OpenSearch cluster. 2. Send an API call to create the OpenSearch credentials for the workspace. 3. Send an API call to create the OpenSearch credentials for your pipelines. 4. Send an API call to create a workspace that you want to connect with your OpenSearch cluster. The pipelines in this workspace will run on your OpenSearch cluster. :::info Security First You can't connect an OpenSearch cluster to an existing workspace. This is because we want your files to be secure. When you create a dedicated workspace connected to your private cloud, you can be certain all your files are stored in your private cloud, not in . This wouldn't be the case if you connected your private cloud to an existing workspace. ::: ## Prerequisites - You must have your Amazon OpenSearch Services clusters ready. We recommend using one cluster for the workspace and another one for your pipelines. - The cluster for your workspace is only used to index the files. It doesn't store any embeddings, so you don't need to allocate too much memory to it. - The cluster for your pipelines handles the vector representations of the files, so make sure you allocate sufficient memory to it. - Both clusters must be in the `eu-central-1` region in AWS. If you need support for another region, contact your representative. - Have the `arn` for your workspace and pipeline clusters ready. You'll add it to the request to create the credentials.
Obtaining the ARN for your clusters 1. Log in to your AWS account and open **Amazon OpenSearch Service**. 2. Select the cluster whose ARN you want to check. The cluster details page opens, and in the _General information_ section, you can see the domain ARN for the cluster.
## Connect Your Cluster to 1. Authorize to use your OpenSearch clusters: 1. Log in to your AWS account and open **Amazon OpenSearch Service**. 2. On the dashboard, select the cluster you want to use for the workspace. (This is the cluster that is used to store the list of files only.) 3. On the cluster details page, go to **VPC endpoints**. 4. In the _Authorized principals_ section, click **Authorize principal** and type in the AWS account number: `364870968120`. 5. Click **Authorize**. 6. Repeat steps 1i to 1v for the cluster you want to use for your pipelines. (This cluster will store the embeddings, so it needs more memory allocated.) 2. Create the credentials for your workspace cluster using the [Add OpenSearch credentials](/docs/api/main/add-opensearch-credentials-api-v-1-infrastructure-document-stores-post.api.mdx) endpoint. The port number is always `443`. Here's a sample request you can use as a starting point: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/infrastructure/document_stores \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data ' { "port": 443, "password": "", "aws_domain_arn": "", "username": "", } ' ``` 3. Wait until you get the response. This may take a couple of minutes, as AWS takes some time to create the connection. The response contains the cluster's credentials ID. You'll need them to create the workspace in the last step. 4. Repeat step 2 for the pipeline cluster. Again, wait for the response and make sure you save the credentials ID from it. :::info Listing Credentials You can also use the [List Available Opensearch Credentials ](/docs/api/main/list-available-opensearch-credentials-api-v-1-infrastructure-document-stores-get.api.mdx) endpoint to get a list of all the credentials created for your organization. ::: 5. Create the workspace that you want to connect to your clusters. Use the [Create Workspace](/docs/api/main/create-workspace-api-v-1-workspaces-post.api.mdx) endpoint. Make sure you provide the workspace cluster and the pipeline cluster credentials IDs you obtained from responses in steps 2 and 3. Here's the code you can use as a starting point for this request: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data ' { "document_store_credentials": { "pipeline_document_store_credentials_id": "", "workspace_document_store_credentials_id": "" }, "name": "" } ' ``` ## What To Do Next Now, the pipelines you create and deploy in the newly created workspace will use the files stored in your OpenSearch cluster. ### Updating Credentials If your credentials to any of the clusters connected to change, you must: 1. [Delete the workspace](/docs/api/main/delete-workspace-api-v-1-workspaces-workspace-name-delete.api.mdx) that uses the credentials. (You can also do this form inferface. For details, see [Navigation](/docs/getting-started/working-in-deepset-cloud.mdx#navigation).) 2. Delete the credentials using the [Delete OpenSearch credentials](/docs/api/main/delete-opensearch-credentials-api-v-1-infrastructure-document-stores-credentials-id-delete.api.mdx) endpoint. 3. [Add the new credentials](/docs/api/main/add-opensearch-credentials-api-v-1-infrastructure-document-stores-post.api.mdx). 4. [Create a new workspace](/docs/api/main/create-workspace-api-v-1-workspaces-post.api.mdx). You can then copy your pipelines over to this workspace. ### Deleting Credentials To delete the credentials used by a cluster, you must first [delete the workspace](/docs/getting-started/working-in-deepset-cloud.mdx#navigation) that uses them and then [delete the credentials](/docs/api/main/delete-opensearch-credentials-api-v-1-infrastructure-document-stores-credentials-id-delete.api.mdx). If you delete the credentials without deleting the workspace, the workspace becomes unusable anyway. ### Backup doesn't create any backups for the data of your pipelines to prevent the data from spreading into 's storage. We highly recommend you configure [automated snapshots](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/managedomains-snapshots.html) for your OpenSearch indexes, as well as create runbooks and regularly practice index recovery. --- ## Connect Your S3 Bucket comes with seamless integration with Amazon S3, a simple storage service by Amazon Web Services. Store your data in an AWS S3 bucket and connect it to d to use the files in S3 in your pipelines. *** ## About This Task You use the API to connect to your Amazon Web Services S3 bucket. There are four steps you must complete: 1. Give an AWS role that can access your S3 bucket. 2. Send an API call to create the S3 credentials for a workspace. 3. Send an API call to create a workspace you want to connect to your S3 bucket. 4. Upload files to this workspace using one of the available methods described in [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx) :::info Security First You can't connect an S3 bucket to an existing workspace. This is because we want your files to be secure. When you create a dedicated workspace connected to your private cloud, you can be certain all your files are stored in your private cloud, not in . This wouldn't be the case if you connected your private cloud to an existing workspace. ::: transfers the files you upload to the workspace to the connected S3 bucket. While you can still view these files in , they are actually stored in S3. Any pipelines created in the workspace will use the files stored in the connected S3 bucket. :::warning Important does not sync files bidirectionally with S3. If you upload files directly to S3 and then connect the bucket to , these files will not be visible or usable in . To use files in pipelines, first connect the bucket to a workspace, then upload the files through the workspace. ::: ## Prerequisites - You can either use an existing AWS S3 bucket, or let CloudFormation create a new one. - Have the name for your bucket at hand. You'll need it for CloudFormation to create a role for , and in the request to create S3 credentials in . - Have your organization ID at hand. Use the [Read Users Me](/docs/api/main/read-users-me-api-v-1-me-get.api.mdx) API endpoint to obtain it. You'll need it when creating a stack in CloudFormation to grant access to your bucket. ## Connect Your S3 Bucket to deepset 1. Add a role for to authorize it to work with your files: 1. In AWS, open _CloudFormation_ and click **Create stack**. 2. Select _Template is ready_. 3. As _template source_, choose _Amazon S3 URL_, paste this URL: `https://deepsetcloud-cloudformation-templates.s3.eu-central-1.amazonaws.com/BringYourOwnCloud/AWS/FileStore/S3Bucket/deepsetCloud-BringYourOwnCloud-AWS-FileStore-S3Bucket_cloudformation.yaml` and click **Next**. 4. Give your stack a name. 5. In the _Parameters_ section: 1. Choose whether you want to use an existing bucket or not. 2. Set the bucket name. 3. Set your organization ID as the _ExternalId_. 4. Set the name for the IAM Role to create. 6. For all other options, leave the default settings. Continue to the last step. 7. On the last step, acknowledge the AWS statement in the Capabilities section and click **Submit**. Wait until the status of your stack changes to CREATE_COMPLETE. 8. Open the stack and go to the _Outputs_ tab. 9. Copy the value of the _RoleARN_ key as you'll need it when sending a request to create the credentials. 2. Add the S3 credentials using the [Add S3 Credentials](/docs/api/main/add-s-3-credentials-api-v-1-infrastructure-file-stores-post.api.mdx) endpoint. Here's a sample request you can use as a starting point: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/infrastructure/file_stores \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data ' { "assume_role": { "role_arn": "", "role_session_name": "" }, "bucket_name": "" } ' ``` `role_session_name` is any name you want to give to this session. 3. Wait for the response. The response contains the ID of the credentials for S3. You'll need it to create the workspace connected to S3. 4. Create the workspace that will use the files stored in S3. Use the [Create Workspace](/docs/api/main/create-workspace-api-v-1-workspaces-post.api.mdx) endpoint and specify the `file_store_credentials`. You can ignore the `document_store_credentials` (it's used for OpenSearch). Here's the code you can use to start with: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data ' { "file_store_credentials": { "file_store_credentials_id": "" }, "name": "" } ' ``` ## What To Do Next You connected your newly created workspace to your S3 bucket. All the files you upload to this workspace will be stored in your S3 bucket, and all the pipelines you create in this workspace will use the files from S3. You can now upload files to your workspace. For instructions, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx) ### Updating Credentials If your credentials to any of the S3 buckets connected to change, do the following: 1. [Delete the workspace](/docs/api/main/delete-workspace-api-v-1-workspaces-workspace-name-delete.api.mdx) that uses the credentials. (You can also do this [from interface](/docs/getting-started/working-in-deepset-cloud.mdx).) 2. Delete the credentials using the [Delete S3 Credentials](/docs/api/main/delete-s-3-credentials-api-v-1-infrastructure-file-stores-credentials-id-delete.api.mdx) endpoint. 3. [Add new credentials ](/docs/api/main/add-s-3-credentials-api-v-1-infrastructure-file-stores-post.api.mdx). 4. [Create a new workspace](/docs/api/main/create-workspace-api-v-1-workspaces-post.api.mdx). You can then copy your pipelines over to this workspace. ### Deleting Credentials To delete the credentials used by a cluster, you must first [delete the workspace](/docs/getting-started/working-in-deepset-cloud.mdx#navigation) that uses them and then [delete the credentials](/docs/api/main/delete-s-3-credentials-api-v-1-infrastructure-file-stores-credentials-id-delete.api.mdx). If you delete the credentials without deleting the workspace, the workspace becomes unusable anyway. ### Backup doesn't create any backups for the data of your pipelines to prevent the data from spreading into 's storage. We highly recommend you configure [regular or continuous backups](https://docs.aws.amazon.com/aws-backup/latest/devguide/s3-backups.html) for your S3 buckets, and create runbooks, and regularly practice index recovery. --- ## Synchronize Data Using Airbyte Airbyte is an open source data integration tool you can use to synchronize your data from various sources to destinations. We've added a connector for the destination so that you can seamlessly transfer your data from various sources to . ## About this Task With Airbyte, you can easily transfer data from your data sources to a workspace. You can also schedule regular data syncs to automate the process. To learn more about Airbyte, visit [their webpage](https://airbyte.com/). You can upload your data from a source that supports the `DocumentFileType` format to a workspace. The currently supported sources are: - Microsoft OneDrive - Microsoft SharePoint - Google Drive - S3 Using the destination connector, you can specify: - The API key. - The workspace where you want to upload the data. - The URL for your deployment. For details, see the [connector documentation](https://docs.airbyte.com/integrations/destinations/deepset). ## Prerequisites - You must have an Airbyte account. - You must have a API key. For details, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). ## Synchronize Data with Airbyte Airbyte is an external service, so we recommend you check their documentation (you can find the links below). Synchronizing data involves three steps: 1. [Add a source](https://docs.airbyte.com/using-airbyte/getting-started/add-a-source). 2. [Add a destination](https://docs.airbyte.com/using-airbyte/getting-started/add-a-destination). Choose the destination connector. You can check its documentation at [](https://docs.airbyte.com/integrations/destinations/deepset). 3. [Set up a connection between source and destination](https://docs.airbyte.com/using-airbyte/getting-started/set-up-a-connection). --- ## Upload Files Upload your data to . The files you upload are then turned into documents and indexed to make them searchable for your pipelines. *** :::info Things to note: - Currently, supports files encoded in UTF-8 format. For files with different encoding formats, you may experience issues with display or formatting. - A single file cannot be larger than 200 MB. If a file exceeds this size, it won't be uploaded. You can use [ SDK](https://sdk.cloud.deepset.ai/0.0.34/) to upload larger files. - Whenever you upload a file, it's indexed by all indexes enabled in this workspace. This means all deployed pipelines then use this file to resolve queries. ::: ## About This Task ### Supported File Types You can upload any file types, there are no restrictions. To preprocess most file types, you can add `Converters` to your index. For the file types for which a converter is unavailable, we recommend preprocessing the files outside of . You can use one of 's integrations to do that. For details, see [Using Hosted Models and External Services](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/supported-connections-and-integrations.mdx). To learn more, see also [PreProcessing Data with Pipeline Components](/docs/how-to-guides/working-with-indexes/prepare-your-data.mdx). Once you upload your files, you can preview them in . Preview is supported for TXT, PDF, JSON, HTML, MD, XML, CSV, DOCX, DOC, XLSX, XLS, PNG, JPG, JPEG, GIF, SVG, and WEBP formats. ### Metadata You can upload files together with metadata if you use the SDK or REST API. When uploading from the interface, you can add metadata to your files one by one once they're already uploaded. If you're uploading files with metadata, the resulting documents inherit the metadata from your files.
Preparing file metadata To add metadata to your files at upload time, create one metadata file for each file you upload. The metadata file must be a JSON file with the same name as the file whose metadata it contains and the extension `meta.json`. For example, if you're uploading a file called `example.txt`, the metadata file should be called `example.txt.meta.json`. If you're uploading a file called `example.pdf`, the metadata file should be `example.pdf.meta.json`. Here's the format of metadata in your `*.meta.json` files: `{"meta_key1": "value1", "meta_key2": "value2"}`.
To learn more about adding metadata, see [Add Metadata to Your Files](/docs/how-to-guides/working-with-your-data/working-with-metadata/add-metadata.mdx). To learn about how to use metadata in your search app, see [Working with Metadata](/docs/how-to-guides/working-with-your-data/working-with-metadata/use-metadata-in-your-search-system.mdx). ### Upload Sessions The SDK and the [Create Upload Session](/docs/api/main/create-upload-session-api-v-1-workspaces-workspace-name-upload-sessions-post.api.mdx) REST API endpoint use upload _sessions_. To start uploading files, you must first create a session. Sessions help you track the files you're uploading. Each session has an ID and you can check the status of your uploaded files at any time. Files start uploading only after a session is closed. If you don't close a session explicitly, it's automatically closed after 24 hours. We recommend using upload sessions for large file uploads as they are faster and more efficient. There's no limit on the number of files per session, but we recommend keeping it to a maximum of 50,000 files. After you upload files to , it may take some time before the files become visible. This diagram explains how the upload sessions work: ## File Updates To learn how enabled indexes handle updated files, see [Indexes](/docs/concepts/indexes/indexes.mdx). ## Choosing the Best Upload Method - If you prefer to upload from and you have a limited number of files, [upload from the UI](#upload-from-the-ui). - If you have a lot of data and metadata to upload and are familiar with coding, [use the SDK](#upload-with-the-sdk). - If the SDK upload doesn't work for you, use the REST API. ## Prerequisites - Make sure you have a workspace to upload your files to. You can easily create one if needed: - 1. In , click the workspace name in the upper left corner. 2. Type the name of the workspace you want to create. You can create up to 100 workspaces. ## Upload from the UI 1. In , go to _Files>Upload Files_. 2. Drag your files and folders to . 3. Click **Upload**. The files may take a while to be processed and displayed on the Files page. ## Upload with the SDK This method is best if you have many files to upload. It makes it possible to add metadata to your files. You can use the command-line interface or Python methods: - [Upload Files with CLI](/docs/how-to-guides/working-with-the-sdk/using-the-command-line-interface-cli/upload-files-with-cli.mdx) - [Upload Files with Python](/docs/how-to-guides/working-with-the-sdk/using-python-methods/upload-files-with-python.mdx) See also our tutorials: - [Tutorial: Uploading Files with Metadata through SDK CLI](/docs/tutorials/learn-the-basics/tutorial-uploading-files-with-cli.mdx) - [Tutorial: Uploading Files with Python Methods](/docs/tutorials/learn-more-advanced-features/tutorial-uploading-files-with-python-methods.mdx) ## Upload with the REST API There are to ways to upload with REST API: - Asynchronously: First, you send a request to open a session. You get a URL and an authentication configuration as a response. You use the URL to upload your files. Then, you close the session. This is when your files are sent to , and the upload is finished. - Synchronously: You simply send a request to the [Upload File](/docs/api/main/upload-file-api-v-1-workspaces-workspace-name-files-post.api.mdx) endpoint. It's not recommended for large number of files. ### Upload in an Upload Session The upload starts after you close a session by sending a request to the [Close Session](/docs/api/main/close-session-api-v-1-workspaces-workspace-name-upload-sessions-session-id-put.api.mdx) endpoint. If you don't explicitly close your session, it's automatically closed after 24 hours. 1. [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). You need this to connect to . 2. (Optional) Prepare your metadata files. See the [Metadata](#metadata) section. 3. Open a session using the [Create Upload Session](/docs/api/main/create-upload-session-api-v-1-workspaces-workspace-name-upload-sessions-post.api.mdx) endpoint. Use this code as a starting point. Replace `` in the URL with the name of your workspace and enter your API key in the `authorization` header: ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//upload_sessions \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' ``` 4. Send your files to the URL you received in the response using the authentication configuration from the response. You can send both your metadata and raw files to this URL. 5. After you send all your files, close the session to start the upload. Use this code as a starting point replacing `workspace_name` in the URL with the name of your workspace and `YOUR_API_KEY` in the `authorization` header with your API key: ```curl curl --request PUT \ --url https://api.cloud.deepset.ai/api/v1/workspaces/workspace_name/upload_sessions/session_id \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' ``` 6. Wait a while until your files are listed in .
An example script to upload files in a session In this scenario, you save the files locally first: ```python from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Tuple, Optional from uuid import UUID from tqdm.asyncio import tqdm # to visualise progress of async task completion DC_ENDPOINT = "https://api.cloud.deepset.ai/api/v1" WORKSPACE_NAME="" API_TOKEN="" log = structlog.get_logger(__name__) def create_session() -> Tuple[UUID, Dict[Any, Any]]: response = httpx.post( f"{DC_ENDPOINT}/workspaces/{WORKSPACE_NAME}/upload_sessions", headers={"Authorization": f"Bearer {API_TOKEN}"}, json={}, timeout=120, ) assert response.status_code == 201 return ( UUID(response.json()["session_id"]), response.json()["aws_prefixed_request_config"], ) def close_session(session_id: UUID) -> None: response = httpx.put( f"{DC_ENDPOINT}/workspaces/{WORKSPACE_NAME}/upload_sessions/{session_id}", headers={"Authorization": f"Bearer {API_TOKEN}"}, json={"status": "CLOSED"}, timeout=120, ) assert response.status_code == 204, f"status code should be '204', got '{response.status_code}' with content '{response.text}'" @dataclass class IngestionStatus: finished_files: int failed_files: int def get_session_status(session_id: UUID) -> IngestionStatus: response = httpx.get( f"{DC_ENDPOINT}/workspaces/{WORKSPACE_NAME}/upload_sessions/{session_id}", headers={"Authorization": f"Bearer {API_TOKEN}"}, timeout=120, ) assert response.status_code == 200 response_body = response.json() print(response_body) return IngestionStatus( finished_files=response_body["ingestion_status"]["finished_files"], failed_files=response_body["ingestion_status"]["failed_files"], ) @dataclass class UploadFileResult: file: str exception: Optional[Exception] = None async def upload_file_to_s3( file_path: str, aws_prefixed_request_config: Dict[Any, Any], semaphore:asyncio.BoundedSemaphore, concurrency=10 ) -> List[UploadFileResult]: client = httpx.AsyncClient() # upload file asynchronously using prefixed request config async with semaphore: async with httpx.AsyncClient( limits=httpx.Limits( max_keepalive_connections=concurrency, max_connections=concurrency ) ) as client: try: async with aiofiles.open(file_path, "rb") as file: file_name = os.path.basename(file_path) content = await file.read() response = await client.post( aws_prefixed_request_config["url"], data=aws_prefixed_request_config["fields"], files={"file": (file_name, content)}, timeout=2000, ) assert response.status_code == 204, f"status code should be '204', got '{response.status_code}'" except Exception as exc: return UploadFileResult(file=file_name, exception=exc) return UploadFileResult(file=file_name) def wait_for_files_to_be_ingested(file_paths, exceptions, session_id): total_uploaded_files = len(file_paths) - len(exceptions) total_processed_files = 0 while total_processed_files < total_uploaded_files: session_status = get_session_status(session_id) log.info( "Polling status", failed_files=session_status.failed_files, finished_files=session_status.finished_files, ) total_processed_files = ( session_status.failed_files + session_status.finished_files ) time.sleep(3) #### the main flow #### async def main(): session_id, aws_prefixed_request_config = create_session() # get a list of files as below, alternatively give a list of explicit paths file_paths = [p for p in Path('./path/to/data/dir').glob('*')] concurrency = 10 semaphore = asyncio.BoundedSemaphore(concurrency) tasks = [] for file_path in file_paths: # upload files tasks.append( upload_file_to_s3(file_path, aws_prefixed_request_config, semaphore=semaphore, concurrency=concurrency) ) results:List[UploadFileResult] = await tqdm.gather(*tasks) exceptions = [r for r in results if r.exception is not None] log.info( "files uploaded", successful=len(results) - len(exceptions), failed=len(exceptions), ) if len(exceptions): log.warning("upload exceptions", exceptions=exceptions) # close session once you are done with uploading # the ingestion will start once the session is closed close_session(session_id) # wait for files to be ingested into deepsetCloud wait_for_files_to_be_ingested(file_paths, exceptions, session_id) if __name__ == '__main__': asyncio.run(main()) ```
You can check the status of your session with the [Get Session Status](/docs/api/main/get-session-status-api-v-1-workspaces-workspace-name-upload-sessions-session-id-get.api.mdx) endpoint. ### Upload with the `Upload File` Endpoint This method is not recommended for uploading more than a few hundred files at once. If you have large numbers of files, upload with the SDK instead. Below are sample requests that you can send to upload your files. For more information, you can also see the [upload file](/docs/api/main/upload-file-api-v-1-workspaces-workspace-name-files-post.api.mdx) endpoint documentation. You need to [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) first. #### Upload an Existing File To upload an existing file, use this code as a starting point for your request: ```curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//files?write_mode=OVERWRITE' \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: multipart/form-data' \ --form 'meta={"key1":"value1", "key2":"value2"}, {"key2":"value2"}' \ --form file=@ ``` Replace the following parameters: - In the URL, replace `YOUR_WORKSPACE_NAME` with the name of your workspace. - In the `authorization` header, replace `YOUR_API_KEY` with your API key. - In the `form file` section, replace `YOUR_FILE.PDF` with the path to your file. - In the `form meta` section, replace `{"key1":"value1", "key2":"value2"}` with the metadata you want to add to your file, if applicable. #### Upload and Create a File To upload and create a file in a single request, use this code as a starting point: ```curl --request POST \ --url 'https://api.cloud.deepset.ai/api/v1/workspaces//files?file_name=myFile.txt' \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: multipart/form-data' \ --form 'meta={"key1":"value1", "key2":"value2"}' \ --form 'text=This is the file text' ``` Replace the following parameters: - In the URL, replace `YOUR_WORKSPACE_NAME` with the name of your workspace and replace `myFile.txt` with the name of the file you want to create and upload. - In the `authorization` header, replace `YOUR_API_KEY` with your API key. - In the `form meta` section, add metadata to your files, if needed. - In the `form text` section, paste the contents of your file. ##### Example Here's a copiable example of both requests, to upload existing files and to upload and create a file in a single request: ```curl # This is an example request to send when you're uploading a file: curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//files \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: multipart/form-data' \ --form 'meta={"key1":"value1", "key2":"value2"}' \ --form file=@ # This is an example request if you're creating the file during upload: curl --request POST \ --url 'https://api.cloud.deepset.ai/api/v1/workspaces//files?file_name=myFile.txt' \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: multipart/form-data' \ --form 'meta={"key1":"value1", "key2":"value2"}' \ --form 'text=This is the file text' ``` --- ## Connect to Your Snowflake Database Query data in your Snowflake database using pipelines. *** ## About this Task provides the `SnowflakeTableRetriever` component that connects to your Snowflake database. To query your Snowflake data, you add this component to your query pipeline. It takes a SQL query as input and returns a database table that matches the query and the generated answer. ## Prerequisites You need the following information about your Snowflake database: - Snowflake account identifier - Snowflake user login - Warehouse name - Schema name - Database name ## Query Your Snowflake Database First, connect to Snowflake through the Integrations page. You can add the integration only for a particular workspace or for the whole organization: Then, add `SnowflakeTableRetriever` to your query pipeline or use one of our ready-made Text-to-SQL pipeline templates. ## Usage Example This is an example of a query pipeline with `SnowflakeTableRetriever` and two Generators: one to translate a natural language query into SQL and send it to `SnowflakeTableRetriever` and another to construct an answer. ```yaml Query pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: "BAAI/bge-m3" ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: "BAAI/bge-reranker-v2-m3" top_k: 5 sql_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a SQL expert working with Snowflake. Your task is to create a Snowflake SQL query for the given question. Refrain from explaining your answer. Your answer must be the SQL query in plain text format without using Markdown. Here are some relevant tables, a description about them, and their columns: {% for document in documents %} Document [{{ loop.index }}] : {{ document.content }} {% endfor %} User's question: {{ question }} Generated SQL query: sql_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 snowflake_retriever: type: haystack_integrations.components.retrievers.snowflake.snowflake_table_retriever.SnowflakeTableRetriever init_parameters: user: "" account: "" authenticator: "SNOWFLAKE" # Choose from: SNOWFLAKE, SNOWFLAKE_JWT, OAUTH warehouse: "" database: "" db_schema: "" replies_to_sql: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: str display_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are an expert data analyst. Your role is to answer the user's question {{ question }} using the information in the table. You will base your response solely on the information provided in the table(s). Do not rely on your knowledge base; only the data that is in the table. Refrain from using the term "table" in your response, but instead, use the word "data". If the table is blank say: "The specific answer can't be found in the database. Try rephrasing your question." Additionally, you will present the table in a tabular format and provide the SQL query used to extract the relevant rows from the database in Markdown. If the table is larger than 10 rows, display the most important rows up to 10 rows. Your answer must be detailed and provide insights based on the question and the available data. SQL query: {{ sql_query }} Table: {{ table }} Answer: display_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: "gpt-4o" generation_kwargs: max_tokens: 2000 temperature: 0 seed: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: sql_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: sql_prompt_builder.prompt receiver: sql_llm.prompt - sender: sql_llm.replies receiver: replies_to_sql.replies - sender: replies_to_sql.output receiver: snowflake_retriever.query - sender: snowflake_retriever.table receiver: display_prompt_builder.table - sender: replies_to_sql.output receiver: display_prompt_builder.sql_query - sender: display_prompt_builder.prompt receiver: display_llm.prompt - sender: display_prompt_builder.prompt receiver: answer_builder.prompt - sender: display_llm.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "sql_prompt_builder.question" - "display_prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` --- ## Add Metadata to Your Files You can add metadata to your files. You can do this when you upload your files through REST API or SDK, or in the platform UI for the files already uploaded. You can then use these metadata as search filters or to boost ranking and retrieval. Metadata acts like tags that help you find the right content. *** ## About This Task ### File and Document Metadata You can add metadata to both files and documents. Documents are text chunks created by indexing files. They're what query pipelines work with and what gets stored in the document store. When you add metadata to a file, that metadata is automatically passed to the documents created from it during processing. You can preview file metadata in the Haystack Enterprise Platform or access it through the API. Document metadata is stored in the document store, but it might not appear in the platform itself, especially for file types we don't support for preview. To view all metadata, use the API endpoints. ### Adding Metadata to Files There are two ways to add metadata to your files: - During upload: You upload metadata along with the actual files. You can use an API endpoint or the Python SDK to do this. When uploading a file, include a corresponding metadata file with the `meta.json` extension. For example, if you have a file called `myfile.pdf`, its metadata would be stored in a separate file called `myfile.pdf.meta.json`. This approach ensures the metadata is associated with the correct file. - Update files already uploaded. You can do it through REST API or platformUI: - Use the [Update File Meta](/docs/api/main/update-file-meta-api-v-1-workspaces-workspace-name-files-file-id-meta-patch.api.mdx) endpoint. - Update the file metadata directly on the Files page in . You can add, edit, and delete metadata for each file. ### Adding Metadata to Documents You can add metadata to documents by automatically labelling uploaded files with an LLM by using [LLMMetadataExtractor](/docs/reference/pipeline-components/data-processing/extract/LLMMetadataExtractor.mdx) in your index. Check the _AI-Generated-Metadata-for-Files_ index template. For detailed instructions and examples, see [Tutorial: Automatically Tagging Your Data with an LLM](/docs/tutorials/learn-the-basics/tutorial-automatically-tagging-your-data-with-an-llm.mdx). ## Metadata Format Metadata is always a dictionary in this format: `{"meta_key1": "value", "meta_key2": "value2"}`. The value for a specific key in a _key:value_ pair must be of the same type across all files. For example, if one file has a key called "category" and its value is of type _string _`{"category":"news"}`, then the values of "category" in all other metadata files must also be strings. An upload will fail if another metadata file lists "category" with a value that's not a string but an integer or some other type. :::info Enforcing Metadata Type You can specify the metadata type by including a type suffix in the key, using the `_type` format. For example, `{ "datefield_text": "today" }` sets the metadata value as a string. Use `_text` to define a metadata field as a string. This type is the most flexible—it includes all other types—so you can use it in any situation. However, if you apply `_text` to a field that normally holds a date range, you won’t be able to filter by date in your searches. In that case, will treat the value as plain text rather than as a date range. ::: :::warning 📢 Important Do not use "`id`" or "`_id`" as metadata keys or values, as they're reserved for internal processing of . If you add them, they'll be overwritten or rejected. ::: ### Formatting Guidelines for Uploading with SDK When uploading with SDK, include one metadata file for each file you're uploading. The name of the metadata file should match the original file's name, but with a `meta.json` extension. Format the metadata inside the metadata file like this: `{"meta_key1": "value", "meta_key2": "value2"}`.
Example metadata file This file contains reviews for the Hotel Park Royal Palace in Vienna. The file is called _austria_trend_hotel_park_royal_palace_vienna_0.txt_. ```Text austria_trend_hotel_park_royal_palace_vienna_0.txt Positives: location and how clean it is Negatives: lack of variety in food any thing you ask for will charge you 5 euro the WiFi is not covering all my room dogs are allowed ``` This is the accompanying metadata file. It's called _austria_trend_hotel_park_royal_palace_vienna_0.txt.meta.json_. ```json austria_trend_hotel_park_royal_palace_vienna_0.txt.meta.json {"Hotel_Address": "Schlossallee 8 14 Penzing 1140 Vienna Austria", "Review_Date": "2016-02-22", "Average_Score": 8.8, "Hotel_Name": "Austria Trend Hotel Park Royal Palace Vienna", "Reviewer_Score": 9.6} ```
### Formatting Guidelines for Uploading with REST API If you're uploading files through the API, pass metadata for each file in a separate dictionary formatted like this: `meta={"key1":"value1", "key2":"value2"}`. For each file you're uploading, provide a corresponding metadata dictionary. The order matters: the first dictionary you pass is linked to the first file, the second dictionary to the second file, and so on. ### Allowed Values In your metadata dictionaries, you can pass the following: - Numerical data - Dates - Keyword fields - Lists Metadata limitations: - One level of nesting works best. - The size limit for a single value in the _key:value_ pair is 32 766 bytes, which is roughly 32 766 characters. - The total size of metadata (all keys and values) is 250 000 bytes maximum, roughly 250 000 characters. ### Example Here are simple examples of metadata: ```python metadata = [{"type": "article", "source": "New York Times", "title": "Leaders Look into the Future", "year published": "2020"}] ``` ```curl { "type": "book", "topic": "business", "author": "Ben Horowitz", "book_titles": [ "The Hard Thing About Hard Things", "What You Do Is Who You Are" ] } ``` ## Add Metadata with the Python SDK The easiest way is to upload metadata together with your files. For detailed instructions, see [Tutorial: Uploading Files with CLI](/docs/tutorials/learn-the-basics/tutorial-uploading-files-with-cli.mdx) or [Tutorials: Uploading Files with Python Methods](/docs/tutorials/learn-more-advanced-features/tutorial-uploading-files-with-python-methods.mdx). ## Add Metadata with REST API Here's the code you can use to add metadata to files when [uploading them through REST API](/docs/api/main/upload-file-api-v-1-workspaces-workspace-name-files-post.api.mdx): ```curl curl --request POST \ --url 'https://api.cloud.deepset.ai/api/v1/workspaces//files?write_mode=OVERWRITE' \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: multipart/form-data' \ --form file=@ // Here is where you define the metadata for your file: --form 'meta={"year":"2009", "type":"financial report"}' ``` Make sure you update the following parameters: - In the URL, update `` to your workspace name. - In the `authorization` header, replace `` with your API key. - In the `form` section: - Replace `` with the path to your file. - Update the metadata. You can also add or update metadata of files that are already uploaded to , using the [Update File Meta](/docs/api/main/update-file-meta-api-v-1-workspaces-workspace-name-files-file-id-meta-patch.api.mdx) endpoint. You need the ID of the file whose metadata you want to change. (You can check it with the [list files](/docs/api/main/list-files-api-v-1-workspaces-workspace-name-files-get.api.mdx) endpoint.) ```curl curl --request PATCH \ --url https://api.cloud.deepset.ai/api/v1/workspaces//files//meta \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ // Here is where you pass the metadata: --data ' { "year": "2009", "type": "financial report" } ' ``` ## Add Metadata from the UI This is an easy way to add, update, and remove metadata from files. 1. Log in to and go to **Files**. 2. Find the file whose metadata you want to update, click **More actions** next to it, and choose **View Metadata**. 3. Update the metadata as needed. You must choose a type for every field and then add its key and value. When you're done, save your changes. 4. Continue for each file whose metadata you want to update. --- ## Filter Syntax Filter with your file's metadata to refine searches and retrieval, ensuring the returned results match the conditions in the filters. *** ## Metadata as Filters Metadata acts as filters that narrow down the scope of your search. All metadata from your files are shown as filters in the Playground. ## How Filters Work Filters operate on metadata attached to your files and documents. The metadata are dictionaries with the `key:value` format. To learn how to add them, see [Add Metadata to Your Files](./add-metadata.mdx). Filters are used to match documents based on specific criteria. A filter contains the name of the metadata field, comparison operator, and value. You can apply them alone or combined using logical operators. ## Filter Structure Filters are defined as nested dictionaries that use explicit operators. They can be of two types: comparison or logic. ### Comparison Comparison filters contain at least one comparison of a metadata field name with a certain value. You can combine multiple comparisons using logical operators that can be nested to achieve complex filters. Each comparison filter must contain the following keys: - `field`: The name of the metadata field. For example, this is how you would filter for a metadata field called "type": `field: type`. - `operator`: A comparison operator, must be one of the following operators: - `==`: Equal, checks if the document field matches the specified value. - `!=`: Not equal, checks if the document field doesn't match the specified value. - `>`: Greater than, compares numerical or date values. - `>=`: Greater than or equal, compares numerical or date values. - `<`: Less than, compares numerical or date values. - `<=`: Less than or equal, compares numerical or date values. - `in`: In, checks if a field contains a specific value. - `not in`: Not in, checks if a field doesn't contain a specific value. - `value`: The metadata field value. When used with `in` and `not in` operators, the value can be a list. ### Logic Logic filters combine multiple conditions to form complex queries. They must contain the following keys: - `operator`: A logical operator, must be one of the following (note that logical operators are capitalized): - `NOT`: The specified condition must not be met. - `AND`: All conditions must be met. - `OR`: At least one of the conditions must be met. - `conditions`: A list of dictionaries defines the conditions that must be met. These dictionaries can be either of type comparison or logic. ### Filters in Playground To see all the filters based on your metadata in Playground: 1. Go to **Playground**. 2. Click the Configurations icon in the top right corner and choose the **Filters** tab. When you select two or more metadata filters, an **AND/OR** toggle appears above the filter list. It controls how multiple filters are combined: - **AND**: Documents must match all selected filter conditions. This is the default setting. - **OR**: Documents must match at least one of the selected filter conditions. ### Examples #### Comparison Filter Here's a simple comparison filter that checks if the value of a document's metadata field `'type"` is `"article"`: ```yaml router: type: haystack.components.routers.metadata_router.MetadataRouter rules: en: # Router's rules use filters: field: meta.type operator: == value: article ``` ```python filters = {"field": "type", "operator": "==", "value": "article"} ``` #### Comparison and Logic Filter Here's a more complex filter combining both comparison and logic filters. For a document to be selected, all of the following conditions must be true, as they're combined using the `AND` operator: 1. The document's type must be "article". 2. The document's date must be on or after January 1, 2015. 3. The document's date must be before January 1, 2021. 4. The document's rating must be 3 or higher. 5. The document must either belong to the genres "economy" or "politics" or it must be published by "The New York Times". ```yaml retriever: type: haystack.components.retrievers.filter_retriever.FilterRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore filters: operator: "AND" conditions: - field: type operator: == value: "article" - field: date operator: == value: 1420066800 - field: date operator: < value: 1609455600 - field: rating operator: < value: 3 - operator: "OR" conditions: - field: genre operator: "IN" value: ["economy", "politics"] - field: publisher operator: == value: "nytimes" ``` ```python filters = { "operator": "AND", "conditions": [ {"field": "type", "operator": "==", "value": "article"}, {"field": "date", "operator": ">=", "value": "2015-01-01"}, {"field": "date", "operator": "<", "value": "2021-01-01"}, {"field": "rating", "operator": ">=", "value": 3}, { "operator": "OR", "conditions": [ {"field": "genre", "operator": "in", "value": ["economy", "politics"]}, {"field": "publisher", "operator": "==", "value": "nytimes"}, ], }, ], } ``` ## Components Using Filters - [`MetadataRouter`](https://docs.haystack.deepset.ai/docs/metadatarouter): You can use filters in the `rules` parameter. - [`Retrievers`](/docs/concepts/about-pipelines/pipeline-components.mdx) For details and usage examples, see the component's documentation page. ## Legacy Filters The syntax of filters in v1.0 didn't require explicit keys for comparison filters and used operators preceded by `$` (the dollar sign). The new syntax is more explicit and easier to understand. We will continue to support the old syntax for now, but we encourage you to gradually migrate to the new filtering syntax. Here's the mapping of operators in both versions: | v.1.0 | v2.0 | | :---- | :----- | | $eq | == | | $ne | != | | $gt | > | | $gte | > = | | $lt | \< | | $lte | \<= | | $in | in | | $nin | not in | Comparison filters in v1.0 didn't explicitly indicate the field name, value, or operator. This is how the same filter expression looks like in both versions: ```python Legacy filter syntax legacy_filter = { "$and": { "type": {"$eq": "article"}, "date": {"$gte": "2015-01-01", "$lt": "2021-01-01"}, "rating": {"$gte": 3}, "$or": {"genre": {"$in": ["economy", "politics"]}, "publisher": {"$eq": "nytimes"}}, } } ``` ```python Current filter syntax current_filter = { "operator": "AND", "conditions": [ {"field": "type", "operator": "==", "value": "article"}, {"field": "date", "operator": ">=", "value": "2015-01-01"}, {"field": "date", "operator": "<", "value": "2021-01-01"}, {"field": "rating", "operator": ">=", "value": 3}, { "operator": "OR", "conditions": [ {"field": "genre", "operator": "in", "value": ["economy", "politics"]}, {"field": "publisher", "operator": "==", "value": "nytimes"}, ], }, ], } ``` --- ## Use Metadata in Your Search System Attach metadata to the files you upload to and take advantage of them in your search system. Learn about different ways you can use metadata. *** ## Applications of Metadata Metadata in can serve as filters that narrow down the selection of documents for generating the final answer or to customize retrieval and ranking. Let's say we have a document with the following metadata: ```json { "title": "Mathematicians prove Pólya's conjecture for the eigenvalues of a disk", "subtitle": "A 70-year old math problem proven", "authors": ["Alice Wonderland"], "published_date": "2024-03-01", "category": "news", "rating": 2.1 } ``` We'll refer to these metadata throughout this guide to illustrate different applications. To learn how to add metadata, see [Add Metadata to Your Files](./add-metadata.mdx). ## Metadata as Filters Metadata acts as filters that narrow down the scope of your search. All metadata from your files are shown as filters in the Playground: But you can also use metadata to add a preset filter to your pipeline or when searching through REST API. ### Filtering with a Preset Filter You can configure your pipeline to use only documents with specific metadata values. The following components support filters through their `filters` parameter: - [`FilterRetriever`](https://docs.haystack.deepset.ai/docs/filterretriever) - [`OpenSearchBM25Retriever`](https://docs.haystack.deepset.ai/docs/opensearchbm25retriever) - [`OpenSearchEmbeddingRetriever`](https://docs.haystack.deepset.ai/docs/opensearchembeddingretriever) (With [`MetadataRouter`](https://docs.haystack.deepset.ai/docs/metadatarouter), you can use filters in the `rules` parameter to route documents matching the filters to specific branches of your pipeline.) For example, to retrieve only documents of the news category (`"category": "news"` in metadata) using FilterRetriever, you could pass this query: ```yaml components: retriever: type: haystack.components.retrievers.filter_retriever.FilterRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" filters: field: meta.category operator: == value: "news" ``` #### Filtering at Query Time with REST API When making a search request [through API](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post.api.mdx), add the filter to the payload when making the request like this: ```curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/WORKSPACE_NAME/pipelines/PIPELINE_NAME/search \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data ' { "debug": false, "filters": { "category": "news", "published_date": "2024" }, "view_prompts": false, "queries": [ "What did Alice write?" ] } ' ``` See also [Filter Syntax](./filtering-logic.mdx). ## Embedding Metadata with DocumentEmbedders `DocumentEmbedders` can vectorize not only the document text but also the metadata you indicate in the `meta_fields_to_embed` parameter. In this example, `SentenceTransformersDocumentEmbedder` embeds the title and subtitle of documents: ```yaml components: document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/e5-base-v2" meta_fields_to_embed: ["title", "subtitle"] ``` This means that the title and subtitle would be prepended to the document content. ## Metadata for Ranking When using `TransformersSimilarityRanker` or `CohereRanker`, you can assign a higher rank to documents with certain metadata values. To learn more about rankers, see `Rankers`. All three rankers mentioned above take the `meta_fields_to_embed` parameter, where you can pass the metadata fields you want to prioritize. Like with DocumentEmbedders, the values of these fields are then prepended to the document content and embedded there. This means that the content of the metadata fields you indicate is taken into consideration during the ranking. In this example, the Ranker prioritizes documents with fields `category` and `authors`: ```yaml components: ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "intfloat/simlm-msmarco-reranker" top_k: 8 meta_fields_to_embed: ["category", "authors"] ``` There's also `MetaFieldRanker`, which sorts documents based on the value of a specific metadata field. It also lets you choose how important the metadata field is in the ranking process. For example, to prioritize documents with the highest rating (assuming the rating is part of the document's metadata), you could use `MetaFieldRanker`: ```yaml components: ranker: type: haystack.components.rankers.meta_field.MetaFieldRanker init_parameters: meta_field: "rating" weight: 1.0 ``` Setting weight to `1.0` means `MetaFieldRanker` only ranks by the metadata field, ignoring any previous rankings or document content. ## Metadata in Prompts You can pass documents' metadata in prompts for additional context and then instruct the LLM to use them. To pass the metadata, you can use the Jinja2 `for` loop that iterates over the documents displaying its number (`loop.index`), title (`doc.meta['title']`), and content (`doc.content`): ```text You are a helpful assistant. Please answer the question based on the following documents: {% for doc in documents %} Document {{ loop.index }}: Title: {{ doc.meta['title'] }} Content: {{ doc.content }} {% endfor %} Question: {{ query }} Answer: """ ``` The syntax for accessing a document's metadata is: `document.meta['metadata_key']`. ## Example Here's an example pipeline that uses metadata during the retrieval, ranking, and answer generation stages. During retrieval, it focuses on documents from the "news" category and embeds the title and subtitle into the document's text. Then, when ranking the documents, it considers the document's title and subtitle. Finally, when generating the answer, it passes the document's published date in the prompt, instructing the LLM to prefer the most recent documents. ```yaml components: bm25_retriever: type: >- haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: >- haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine top_k: 20 custom_query: > query: bool: must: - multi_match: query: $query type: most_fields fields: - content - title - authors operator: OR filter: term: category: news document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: >- haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 model_kwargs: torch_dtype: torch.float16 meta_fields_to_embed: - title - subtitle prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: >- You are a media expert. You answer questions truthfully based on provided documents. For each document, check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document. e.g. [3], for Document[3]. The reference must only refer to the number that comes in square brackets after passage. Otherwise, do not use brackets in your answer and reference ONLY the number of the passage without mentioning the word passage. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. For contradictory information, prefer recent documents. These are the documents: {% for doc in documents %} Document {{ loop.index }}: Title: {{ doc.meta['title'] }} Subtitle: {{ doc.meta['subtitle'] }} Published Date: {{ doc.meta['published_date'] }} Content: {{ doc.content }} {% endfor %} Question: {{ question }} Answer: llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 answer_builder: type: >- deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm FilterRetriever: type: haystack.components.retrievers.filter_retriever.FilterRetriever init_parameters: document_store: type: >- haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine filters: category: news connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: llm.replies receiver: answer_builder.replies - sender: FilterRetriever.documents receiver: document_joiner.documents max_loops_allowed: 100 metadata: {} inputs: query: - bm25_retriever.query - ranker.query - prompt_builder.question - answer_builder.query filters: - bm25_retriever.filters - FilterRetriever.filters outputs: documents: ranker.documents answers: answer_builder.answers ``` ## Related Information - [Filter Syntax](./filtering-logic.mdx) - [Add Metadata to Your Files](./add-metadata.mdx) --- ## Haystack Enterprise Platform Documentation Knowledge Graph This knowledge graph represents the structure and relationships between documentation topics in the dc-docs repository (Haystack Enterprise Platform documentation). ## Main Documentation Areas ```mermaid graph TB Root[Haystack Enterprise Platform Documentation] Root --> GettingStarted[Getting Started] Root --> Learn[Learn] Root --> Concepts[Concepts] Root --> HowTo[How-To Guides] Root --> Tutorials[Tutorials] Root --> API[API Reference] Root --> Builder[Builder] style Root fill:#2563eb,stroke:#1e40af,color:#fff style GettingStarted fill:#059669,stroke:#047857,color:#fff style Learn fill:#dc2626,stroke:#b91c1c,color:#fff style Concepts fill:#7c3aed,stroke:#6d28d9,color:#fff style HowTo fill:#ea580c,stroke:#c2410c,color:#fff style Tutorials fill:#0891b2,stroke:#0e7490,color:#fff style API fill:#4b5563,stroke:#374151,color:#fff style Builder fill:#65a30d,stroke:#4d7c0f,color:#fff ``` ## Core Concepts Relationships ```mermaid graph LR subgraph Core["Core Concepts"] Pipelines[Pipelines] Components[Pipeline Components] Indexes[Indexes] DocStores[Document Stores] Data[Data Flow] LLMs[Language Models] Jobs[Jobs] Agents[AI Agents] end Pipelines -->|contain| Components Pipelines -->|use| Indexes Pipelines -->|connect to| DocStores Pipelines -->|use| LLMs Pipelines -->|run as| Jobs Pipelines -->|can include| Agents Indexes -->|write to| DocStores Indexes -->|process| Data Components -->|read from| DocStores Components -->|use| LLMs Agents -->|use| Components Agents -->|call| Tools[Agent Tools] Agents -->|maintain| Memory[Agent Memory] style Pipelines fill:#2563eb,stroke:#1e40af,color:#fff style Components fill:#7c3aed,stroke:#6d28d9,color:#fff style Indexes fill:#059669,stroke:#047857,color:#fff style DocStores fill:#dc2626,stroke:#b91c1c,color:#fff style Agents fill:#ea580c,stroke:#c2410c,color:#fff ``` ## Pipeline Components Ecosystem ```mermaid graph TB subgraph ComponentTypes["Component Types"] Embedders[Embedders] Generators[Generators] Retrievers[Retrievers] Rankers[Rankers] Builders[Builders] Converters[Converters] Preprocessors[Preprocessors] Joiners[Joiners] Routers[Routers] Writers[Writers] end subgraph Providers["Model Providers"] OpenAI[OpenAI] Anthropic[Anthropic] Cohere[Cohere] AmazonBedrock[Amazon Bedrock] GoogleVertex[Google Vertex] HuggingFace[Hugging Face] Nvidia[Nvidia] Ollama[Ollama] end Embedders -->|powered by| Providers Generators -->|powered by| Providers Rankers -->|powered by| Providers Converters --> Preprocessors Preprocessors --> Embedders Embedders --> Retrievers Retrievers --> Rankers Rankers --> Builders Builders --> Generators Generators --> Writers style ComponentTypes fill:#f3f4f6,stroke:#9ca3af style Providers fill:#fef3c7,stroke:#fbbf24 ``` ## Document Stores Relationships ```mermaid graph TB subgraph DocStores["Document Stores"] OpenSearch[OpenSearchCore Store] Elasticsearch[Elasticsearch] Pinecone[Pinecone] Weaviate[Weaviate] Qdrant[Qdrant] MongoDB[MongoDB Atlas] PgVector[PgVector] Snowflake[Snowflake] end subgraph Components["Components That Use Stores"] DocWriter[DocumentWriter] BM25[BM25 Retriever] Embedding[Embedding Retriever] Hybrid[Hybrid Retriever] end OpenSearch -->|core managed| DocWriter OpenSearch -->|retrieve from| BM25 OpenSearch -->|retrieve from| Embedding Elasticsearch --> DocWriter Pinecone --> DocWriter Weaviate --> DocWriter Qdrant --> DocWriter MongoDB --> DocWriter PgVector --> DocWriter style OpenSearch fill:#2563eb,stroke:#1e40af,color:#fff style DocWriter fill:#059669,stroke:#047857,color:#fff ``` ## Data Flow ```mermaid graph LR subgraph Upload["Data Upload"] Files[Files] S3[AWS S3] VPC[Private VPC] end subgraph Indexing["Indexing Process"] Index[Index] Preprocess[Preprocessing] Documents[Documents] end subgraph Storage["Storage Layer"] DocStore[Document Store] Database[SQL Database] end subgraph Query["Query Pipeline"] UserQuery[User Query] Retriever[Retriever] GenOrLLM[Generator or LLM] AnswerBuilder[Answer builder] Answer[Answer] end Files --> S3 Files --> VPC S3 --> Index VPC --> Index Index --> Preprocess Preprocess --> Documents Documents --> DocStore Files -->|metadata| Database UserQuery --> Retriever DocStore --> Retriever Retriever --> GenOrLLM GenOrLLM --> AnswerBuilder AnswerBuilder --> Answer Answer -->|results| Database style Upload fill:#dbeafe,stroke:#3b82f6 style Indexing fill:#dcfce7,stroke:#22c55e style Storage fill:#fce7f3,stroke:#ec4899 style Query fill:#fef3c7,stroke:#f59e0b ``` ## AI Agents Architecture ```mermaid graph TB subgraph Agent["AI Agent System"] AgentComp[Agent Component] LLM[Language Model] Memory[Agent Memory] Tools[Agent Tools] end subgraph ToolTypes["Tool Types"] Pipelines[Pipelines] CustomFunc[Custom Functions] MCP[MCP Servers] WebSearch[Web Search] end UserInput[User Input] --> AgentComp AgentComp --> LLM LLM -->|decides| Tools Tools -->|execute| ToolTypes ToolTypes -->|results| LLM LLM -->|output| Memory Memory -->|context| LLM LLM --> Answer[Answer] style AgentComp fill:#ea580c,stroke:#c2410c,color:#fff style Tools fill:#7c3aed,stroke:#6d28d9,color:#fff style Memory fill:#059669,stroke:#047857,color:#fff ``` ## How-To Guides Organization ```mermaid graph TB HowTo[How-To Guides] HowTo --> BuildingAgents[Building Agents] HowTo --> DesigningPipelines[Designing Pipelines] HowTo --> WorkingWithIndexes[Working with Indexes] HowTo --> WorkingWithData[Working with Data] HowTo --> Searching[Searching] HowTo --> Evaluating[Evaluating] HowTo --> Optimizing[Optimizing] HowTo --> Productionizing[Productionizing] HowTo --> ManagingAccess[Managing Access] HowTo --> WorkingWithJobs[Working with Jobs] HowTo --> UsingSDK[Using SDK] DesigningPipelines --> CreatePipeline[Create Pipeline] DesigningPipelines --> DeployPipeline[Deploy Pipeline] DesigningPipelines --> EditPipeline[Edit Pipeline] DesigningPipelines --> WorkWithLLMs[Work with LLMs] DesigningPipelines --> CustomComponents[Custom Components] DesigningPipelines --> HostedModels[Hosted Models] BuildingAgents --> ConfigureAgent[Configure Agent] BuildingAgents --> AdvancedConfig[Advanced Config] BuildingAgents --> MinimalAgent[Minimal Agent] BuildingAgents --> Troubleshooting[Troubleshooting] style HowTo fill:#ea580c,stroke:#c2410c,color:#fff ``` ## Learning Path ```mermaid graph LR subgraph Learn["Learn Section"] Basics[5-Step Guide] AppComponents[App Components] DocRetrieval[Document Retrieval] Extractive[Extractive QA] RAG[RAG QA] LLMOverview[LLM Overview] PromptEng[Prompt Engineering] MCP[Model Context Protocol] end Basics --> AppComponents AppComponents --> DocRetrieval DocRetrieval --> Extractive Extractive --> RAG RAG --> LLMOverview LLMOverview --> PromptEng style Basics fill:#059669,stroke:#047857,color:#fff style RAG fill:#dc2626,stroke:#b91c1c,color:#fff ``` ## Tutorials Journey ```mermaid graph TB Tutorials[Tutorials] subgraph Basics["Learn the Basics"] FirstSearch[First Document Search] FirstQA[First QA App] RobustRAG[Robust RAG System] DataCleaning[Data Cleaning Agent] PII[PII Masking] MongoDB[MongoDB RAG] AutoTagging[Auto-tagging with LLM] ConnectUI[Connect to UI] UploadCLI[Upload with CLI] end subgraph Advanced["Learn Advanced Features"] CustomComponent[Custom Component] DemoApp[Demo Your App] PythonUpload[Upload with Python] end subgraph RESTAPI["REST API Tutorials"] ChatApp[Chat App API] FeedbackAPI[Feedback API] end Tutorials --> Basics Tutorials --> Advanced Tutorials --> RESTAPI FirstSearch --> FirstQA FirstQA --> RobustRAG style Tutorials fill:#0891b2,stroke:#0e7490,color:#fff ``` ## Cross-Cutting Concerns ```mermaid graph TB subgraph CrossCutting["Cross-Cutting Concerns"] Security[Secrets & Integrations] Roles[User Roles & Permissions] Workspaces[Workspaces] Organizations[Organizations] Settings[Settings] Status[Platform Status] end subgraph AllAreas["Affects All Areas"] Pipelines2[Pipelines] Indexes2[Indexes] Data2[Data] Agents2[Agents] end Security -.->|secures| AllAreas Roles -.->|controls access| AllAreas Workspaces -.->|contains| AllAreas Organizations -.->|manages| Workspaces style CrossCutting fill:#f3f4f6,stroke:#9ca3af ``` ## Component Providers and Integrations ```mermaid graph TB subgraph Haystack["Haystack Components"] HaystackCore[Core Components] Embedders2[Embedders] Generators2[Generators] Retrievers2[Retrievers] Preprocessors2[Preprocessors] Builders2[Builders] end subgraph DeepsetCustom["deepset Custom Nodes"] Augmenters[Augmenters] Code[Code] Crawler[Firecrawl] DeepsetGen[deepset Generators] DeepsetConv[deepset Converters] end subgraph ThirdParty["Third-Party Integrations"] OpenAI2[OpenAI] Anthropic2[Anthropic] Cohere2[Cohere] Bedrock2[Amazon Bedrock] Vertex2[Google Vertex] Nvidia2[Nvidia] Jina2[Jina] Voyage2[Voyage] Mistral2[Mistral] end HaystackCore --> Embedders2 HaystackCore --> Generators2 HaystackCore --> Retrievers2 HaystackCore --> Preprocessors2 HaystackCore --> Builders2 ThirdParty -.->|powers| HaystackCore ThirdParty -.->|powers| DeepsetCustom style Haystack fill:#2563eb,stroke:#1e40af,color:#fff style DeepsetCustom fill:#059669,stroke:#047857,color:#fff style ThirdParty fill:#fef3c7,stroke:#fbbf24 ``` ## Documentation Structure Summary ### Top-Level Organization File counts are MDX pages under `docs/` (approximate; rerun `find` when restructuring). 1. **Getting Started** (~37 files) - Basic concepts - Quick start guide - What's new (releases) - Platform status - Settings management - Working in Haystack Enterprise Platform 2. **Learn** (~9 files) - 5-step guide to prototyping - Document retrieval - Extractive QA - RAG QA - LLM overview - Prompt engineering - Model Context Protocol 3. **Concepts** (~26 files under `docs/concepts/`) - Pipelines (including examples and multimodal topics) - AI Agents - Document stores - Indexes - Data in the platform - Language models - Jobs - Roles, secrets, and integrations (cross-cutting) 4. **Reference — Pipeline components** (~234 files under `docs/reference/pipeline-components/`) - AI components (for example, `Agent`, `LLM`) - Knowledge retrieval, data processing, logic and flow - Third-party integrations (provider-specific components) - Custom `Code` and workspace custom components - Legacy and deprecated components - Input, output, and overview pages 5. **How-To Guides** (~107 files) - Building agents - Designing pipelines (including smart connections and hosted models) - Working with indexes and data - Searching, evaluating, optimizing - Productionizing, managing access, jobs - Using the SDK and REST API workflows 6. **Tutorials** (~14 files) - Learn the basics (9 tutorials) - Learn advanced features (3 tutorials) - REST API tutorials (2 tutorials) 7. **API Reference** (~227 files) - Main REST API (OpenAPI-generated pages) - Jobs API and related endpoints 8. **Builder** (1 file) - Deploy with Hayhooks ## Key Relationships Summary ### Primary Dependencies - **Pipelines** depend on Components, Indexes, Document Stores, and LLMs - **Indexes** depend on Document Stores and process Data - **Components** depend on Document Stores and LLMs - **AI Agents** depend on Components, Tools, and maintain Memory - **Query pipelines** depend on enabled Indexes - **Document Stores** are used by both Indexes (write) and Retrievers (read) ### Data Flow Path 1. Files → Upload to S3/VPC 2. Files → Index (preprocessing) 3. Index → Documents → Document Store 4. User Query → Retriever → Document Store 5. Retriever → Documents → Generator or LLM 6. Generator or LLM → Answer builder (`DeepsetAnswerBuilder` or Haystack `AnswerBuilder`) → Answer ### Agent Workflow 1. User Input → Agent Component 2. Agent → LLM (with tools list) 3. LLM → Tool Call OR Direct Answer 4. Tool → Execution → Result 5. Result → Check Exit Condition 6. Continue loop or return answer ### Component Pipeline Files → Converters → Preprocessors → Embedders → (Storage) → Retrievers → Rankers → Prompt builders → Generators or LLM → Answer builders → Output Smart connections can merge compatible lists (for example, multiple retrievers into one `documents` input) and convert between some types (for example, `string` and `ChatMessage`), which reduces the need for joiners and adapters in many pipelines. ## Cross-References and Integration Points - **Security & Access**: Applies to all pipelines, indexes, and data - **Workspaces**: Contain pipelines, indexes, and files - **Organizations**: Contain multiple workspaces - **Jobs**: Can run any pipeline type - **LLMs**: Used by Generators, ChatGenerators, the `LLM` component, and Agents - **Document Stores**: Central to both indexing and querying - **Embedders**: Must use same model in indexing and query pipelines - **Agents**: Can use pipelines as tools ## Special Component Combinations Common patterns documented: - Retriever + Ranker - PromptBuilder + Generator - ChatPromptBuilder + ChatGenerator - Embedder + Retriever - Joiner + Ranker (often replaceable with smart connections) - Generator or LLM + `DeepsetAnswerBuilder` (RAG answers with references in the UI) or Haystack `AnswerBuilder` - `Input` (`messages`) + `Agent` (minimal agent pipelines) - Router + Multiple paths - Validator + Loop --- ## 5-Step Guide to Building a Successful Prototype Creating a successful AI-based application requires careful planning and execution. This guide outlines five essential steps to help you navigate the process, from identifying your use case to testing your prototype. *** ## Step 1: Identify Your Use Case ### Brainstorm and Prioritize Gather your business and technical teams to brainstorm potential use cases for your LLM app. It’s crucial the team consists of business and technical people. Business teams know and understand business problems, while technical experts can spot what’s doable. Make sure everyone understands the business value of each use case. For each idea, ask: 1. How much value would solving this problem bring? 2. How much effort would it take to solve this problem? Choose use cases that offer high impact without draining your resources. Aim for a working system that delivers value and functionality, even if it’s not polished yet. As your first choice, look for use cases that don’t require spending time on data preparation. Make sure you can easily access the data, it’s in a format you can consume, and you have permissions to use it. When estimating the effort needed to build your solution, remember that it’s often the best choice to start small. AI doesn’t need to replace your whole workflow. Improving one small part of it can already be a big win. ## Step 2: Assemble Your Team To build a successful prototype, you need these key players: ### Must-Have Team Members These are the team members you must have on your team. Otherwise, you’ll miss valuable expertise. - **Product Leader**: Sets the vision, works with stakeholders, and keeps delivery on track. - **AI Engineer**: Knows AI, vector databases, and prompting. Has a product-focused mindset and understands the current LLM and AI landscape. Choose someone who shipped great products before. - **Domain Expert**: Gives advice and tests the app. This will be the subject matter expert who looks at the app from the content perspective. ### Additional Team Members Depending on your app, you might also want: - **Backend Engineer**: Handles the server side of your app and ensures that it's scalable, performant, and secure, among other things. - **Frontend Engineer**: Creates a user-friendly interface and ensures your app is responsive, accessible, and performant. - **UI/UX Designer**: Ensures your app provides a positive and meaningful experience for its users. Conducts user research, designs how users interact with your app, and creates designs for the frontend engineer. - **DevOps Engineer**: Manages and provisions infrastructure, implements systems for monitoring and logging, sets up CI/CD pipelines, ensures efficient allocation of computing resources, and more. - **Data Engineer**: Ensures data quality and consistency. Ensure that your team has a balanced mix of skills to handle all aspects of development. :::tip Team structure when using handles infrastructure, replacing the need for DevOps and Backend Engineers. It offers a customizable testing interface, so you might not need a Frontend Engineer or UX Designer right away. handles most of the data lifecycle, potentially eliminating the need for a dedicated Data Engineer. ::: ## Step 3: Match Your Use Case to the Technology At this stage, you plan your app’s architecture, including its components, inputs, and outputs and how the app arrives at the desired output. ### Define Inputs and Outputs Clearly outline what the user inputs into your system and the expected outputs. This ensures the app meets user needs and fits existing workflows. Think about: - What’s the input? Text? Images? Audio? - How will users phrase their queries? Natural language or keywords? - What output do users expect? This could be generated answers, extracted information, a list of documents, generated code, and so on. Examples of inputs and outputs for common AI-based systems: - **Recommendation system** - Input: User’s browsing history and preferences - Output: List of recommended products or articles - **Chatbot** - Input: User’s text or voice query - Output: Relevant information, suggested actions, answers to questions - **Sentiment analysis tool** - Input: Customer reviews or social media posts - Output: Sentiment scores (positive, negative, neutral) - **Image recognition tool** - Input: Uploaded images or photos - Output: Object labels, scene description, detected faces - **Question answering system** - Input: User’s question in natural language - Output: Extracted or generated answer ### Sketch System Architecture Create a rough sketch of your system architecture. Identify the components that will handle the inputs and outputs. Take into account security: - Is it an internal application? You might need fewer security controls. - Is it high-risk? Plan for strict security controls. Include safeguards against prompt injections and hallucinations. :::info Building with offers templates with built-in safeguards against prompt injections. ::: For an outline of the elements of an LLM system, see [Components of an AI-Based App](/docs/learn/components-of-an-ai-based-app.mdx). ## Step 4: Build Your Prototype Get into the building mode. Your goal is to build a testable prototype as fast as possible. Follow these guidelines: - Optimize for speed. Prioritize quick delivery over scalability. Don’t get lost in the details. - Make it realistic. Your prototype must operate on the data you’ll use in production. Make sure it captures all inputs and outputs. - Document everything. Keep track of all data and processes involved. - Don’t optimize for scale yet. You first need to verify that what you’re building brings value. - Make your prototype interactive. Users must be able to ask a question and get an answer. They must be able to see the value of your app already at this stage. ### Timelines Aim to build your prototype in 1 to 4 weeks. Don’t spend longer – you still need to validate your ideas. ## Step 5: Test Your Prototype Time to ship to actual users. Start small: 1. Release to 5 to 10 users, gather feedback, and fix major issues. Include Subject Matter Experts or users who will actually use your system, such as those paying for your services. Aim to gather around 100 queries or more. This should be sufficient to find the weak and strong points of your app. 2. Tweak and release to a few hundred users. For internal apps, let all your users test it. At this stage, you want to collect as many queries as possible. Make sure users understand how the app works, what data it uses, and what outputs to expect. You may need to educate them on what questions or inputs work and don't work. Ask them to give feedback on each answer. If security matters, encourage users to try breaking it. You can send all these as guidelines to your users before they start testing. ### Analyzing Feedback After testing, you’ll have a list of issues to fix before going live. Building an AI-based app is a cycle of test-improve-test. You should constantly monitor your app and gather feedback. Feedback always skews negatively as people are more likely to give negative feedback than positive feedback. Having this in mind, think about the minimal performance you need for your app. 60% of good feedback may already be sufficient. When analyzing feedback, look for signs of value: - How often was the app used? - Do users come back after their first try? - Can you spot any usage patterns? ### Moving to Production Before going live, check: - **Performance**: Does your app meet the expected response time? Is it fast enough? - **Scalability**: Can it handle the expected number of requests a minute or a day? - **Security**: Do you have all the security controls you need? By following these steps, you can build a robust LLM application that meets your business needs and delivers measurable value. --- ## Components of an AI-Based App Before you start building your app, it’s crucial to understand its components. An LLM app isn’t just about the language model – it’s a system of components working together to deliver results. *** ## Knowledge Base A repository of information your app can reference to provide accurate and relevant responses. This can be a simple document store with text data, a vector store for embeddings, or a structured database. ## Context Retrieval This component finds relevant information to give context to the model. If your app uses existing data rather than user-uploaded content, you’ll need context retrieval, like a search function. This may be a simple keyword search, semantic search, or both. You might also include a ranking tool to prioritize information. For example, you could highlight the latest data or entries with specific metadata. The type of context retrieval you choose depends on your app's purpose and desired output. ## Prompt Rendering This component builds effective prompts by combining user input, retrieved context (like documents), and predefined templates with placeholders for dynamic content. The rendered prompt then goes to the LLM for processing. ## LLM Integration This is the interface with the large language model, either through an API or a local deployment. It takes the rendered prompt and answers queries based on the instructions. It’s the heart of your application. Consider trying different models to balance performance and costs. We recommend making this component flexible enough to switch between models easily. ## Decision Component Depending on your system requirements, you might want a component that chooses different paths based on the data it receives. For example, in a customer service app, you could route happy customers to a chatbot and upset customers to a human agent. ## Output Processing This component formats and potentially filters LLM’s responses. It might involve text cleaning or creating objects that your interface can easily display. ## Feedback Collection This crucial component gathers and stores user feedback. It helps you understand how well your app performs and what needs improvement. Make sure your test users can easily share their thoughts on your system's answers. --- ## Document Search A document search system returns whole documents relevant to the query. It’s useful if you’re not looking for a specific answer but rather want to explore and understand the context around your query. *** ## Document Search Applications Document search is the base for almost any pipeline in . If you’re building a retrieval-augmented generation (RAG) pipeline, document search is the part that feeds the correct document to the large language model (LLM). If you’re building an extractive question answering (QA) pipeline, the QA model can only find answers in the documents retrieved by the document search part of the pipeline. ## How Does It Work? Document search systems help you find the documents related to your query. The basic component of a document search system is the Retriever. When given a query, the Retriever reviews all documents in your database and fetches the most relevant ones. ### Retrieval Types You can use two types of retrievers in your document search system: keyword-based and vector-based. You can also combine them to take advantage of their strengths. #### Keyword-Based Retrieval This retrieval type uses a keyword-based retriever. An example of such a retriever is `OpenSearchBM25Retriever`. Keyword retrievers work with keywords, looking for words shared between the document and the query. They operate on a bag-of-words level and don’t consider the order of words or their contextual meanings, which means they may not capture semantic nuances as effectively as dense retrievers. These retrievers don’t need any training, are fast and effective, and can work in any language and any domain. #### Vector-Based Retrieval This retrieval type relies on vector-based retrievers, such as [OpenSearchEmbeddingRetriever](https://docs.haystack.deepset.ai/docs/opensearchembeddingretriever). Vector retrievers use a model to transform both the documents and the query into numerical vectors (embeddings). Then, they compare both embeddings and, based on that, fetch the documents most similar to the query. Vector retrievers are very good at capturing nuances in queries and documents, recognizing similarities that go beyond keyword matching. They can recognize contextual and semantic information about words and their relationships within a sentence. Unlike keyword retrievers, vector retrievers need to be trained. This means they perform best in the domain and language they were trained on. They’re also more computationally expensive than keyword-based retrievers. #### Hybrid Retrieval Keyword retrievers are fast and can quickly reduce the number of candidate documents. Vector retrievers are better at capturing semantic nuances, thus improving the relevance of search results. For example, keyword searches are best when searching for product IDs. When given the query “P12642,” a sparse retriever would fetch “Miura climbing shoes” as a result. Such a query would throw off dense retrievers since they can return results with a similar product ID. On the other hand, a query like “What are EVs?” would be easier for vector-based retrievers. They would retrieve results like “Electric cars are..” while keyword retrievers would look for the exact keyword match. Combining both retrieval methods in one system makes it more robust for different kinds of queries and documents. Once the retrievers fetch the most relevant documents, you can use a combination strategy to produce the final ranking and return the top documents as search results. A good use case for hybrid retrieval is when your documents are from a niche domain, and it’s unlikely the model was trained on it. Hybrid retrieval saves you the time and money you’d need to train or fine-tune a model, and it’s a good trade-off between speed and accuracy. ## Ranking Documents You can add an additional ranking step to your document search system to sort your documents by relevance, the time they were created, or their metadata field values. This can improve retrieval as some ranking models are more powerful and better than retrievers at determining which documents are relevant. Adding a ranker also makes it possible to consider metadata when ranking documents. The way ranking works is: 1. The retriever fetches documents from the document store. 2. The ranking component goes through the documents the retriever fetched and ranks them according to the criteria specified. This may mean putting the most relevant documents first, or ordering documents based on their recentness, and so on. 3. The ranked documents are displayed as results. Ranking may take some time and make the system slightly slower, especially if you use CohereRanker or SentenceTransformersRanker, but there are scenarios where it's crucial to ensure the desired performance. One example is a system that searches through news articles, where the recentness of the articles plays a crucial role. ## Applications Document search is best suited for scenarios where users do not seek a specific, concise answer but want to explore a topic and understand its context. Some common applications include: - Web search engines - Academic paper search - Legal document search - Enterprise search running on internal databases. ### Retrieval-Augmented Generation Document search is also the first stage in RAG, where the retriever chooses the documents to pass in the prompt to the LLM. The LLM then generates the answer based on these documents rather than its inherent knowledge. This puts a lot of responsibility on the retriever - if the LLM gets incorrect documents, it will generate an incorrect answer. ## Document Search in offers the following components for building information retrieval systems: - `Retrievers` - you can choose from both vector-based and keyword-based retrievers. - `Rankers` - for ordering documents based on your specified criteria. You can use one of the ready-made templates to get you started. Here’s what an example document search system could look like: When given a query, the keyword and vector retrievers fetch relevant documents. DocumentJoiner then combines the documents from both retrievers and a ranker ranks these documents. As a result, you get a list of the most relevant documents ranked based on the criteria you specified. ### Considerations Here’s what you should consider before you start building your document search system: - Which retriever do you want to use: keyword-based, vector-based, or both? How you preprocess documents depends on the type of retriever you use. For keyword-based retrievers, you can split your documents into bigger chunks. For vector-based retrievers, you need to adjust the size of documents to the number of tokens the retriever model can process. Check how many tokens the model was trained on and split your documents into chunks within the model token size limit. Usually, chunks of ~250 words work best. If you’re using hybrid retrieval, you also adjust the document size to the model of the vector-based retriever. You specify the document size using the `split_length` setting of DocumentSplitter: ```yaml splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 ``` - If you chose a vector-based retriever, you must use an `Embedder` with it to turn the documents and the query into vectors. What model do you want to use to embed the texts? You can check our [Embedding Models](/docs/concepts/language-models-in-deepset-cloud.mdx) overview for guidance. - Do you want to embed your documents’ metadata? This is possible with EmbeddingRetriever, CohereRanker, and SentenceTransformersRanker. You can vectorize not only document text but also document metadata. For example, if your system will run on company reports, you may embed the name of the company a report comes from if it’s in the document metadata. To do this, pass the names of the metadata fields in the `meta_fields_to_embed` parameter of the embedder, for example: ```yaml document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/multilingual-e5-base" device: null meta_fields_to_embed: [title, company] ``` --- ## Extractive Question Answering This type of question answering (QA) extracts answers directly from the documents by highlighting the span of text that makes up the answer. *** ## How Does It Work? Extractive QA systems help you find answers to questions within your documents. The documents are processed by a reader model, which identifies and highlights the relevant answers. Unlike generative QA systems, extractive QA systems don't generate new text. Instead, they focus on extracting information from the documents you provide. Here's an example of what an answer in an extractive QA system may look like: ## Advantages Extractive QA systems offer several benefits: - Factual accuracy: They provide factual answers that you can easily verify because they're highlighted directly in the source. - Efficiency: Extractive QA systems are often more computationally efficient compared to generative QA systems. Extracting an answer is faster than generating it, and the models used in extractive QA are smaller than those used in generative QA. - Handling large volumes of text: These systems are well-suited for handling and extracting answers from long documents, such as books or research papers. - Ability to fine-tune the model: The models used in extractive QA systems are relatively small, and it's easy to train them on your own data. ## Challenges Extractive QA systems also come with a set of challenges you should be aware of: - Out-of-scope questions: Extractive QA systems excel when providing answers that are present verbatim in the text. They struggle with questions that require synthesizing information or generating answers not directly stated in the document text. - Document format: Tables may be challenging for extractive QA, as it performs best on textual documents. - Quality of source data: The accuracy of an extractive QA system heavily depends on the quality of the documents it runs on, as it can't generate answers on its own. ## Extractive QA in A basic extractive QA pipeline in combines a `Retriever` and an `ExtractiveReader`. When given a query, the Retriever scans all your documents and retrieves only the ones relevant to the query. It then passes them on to the Reader, which goes only through the retrieved documents and highlights the correct answers. This combination ensures optimal speed and accuracy. comes with ready-made templates for creating an extractive QA pipeline. These templates work well out of the box, so you only need to modify the name. --- ## Retrieval Augmented Generation (RAG) Question Answering Generative question answering (QA) uses large language models (LLMs) to generate human-like, novel responses to user queries. Learn about its advantages, challenges, and how generative QA is done in . *** ## What's RAG QA? RAG question answering uses large language models to generate human-like responses to user queries in question-answering apps. Instead of simply extracting answers from existing documents, generative systems create new text based on instructions provided in the prompt. A prompt is a specific instruction given to the model in natural language to help it understand the task and generate an appropriate response. To build a basic RAG QA system, you need a large language model (LLM), like GPT-4, and a simple prompt. Based on the prompt, the model generates an answer. ## Advantages RAG QA offers several advantages compared to extractive QA: - Extracting information from multiple sources: The system can extract and combine information from various sources to produce coherent and informative answers from scratch. - Generating original content: LLMs go beyond extracting existing answers and produce more creative and personalized responses. You can use them to create a system that matches your brand voice or feels like talking to a real human. - Language flexibility: LLMs are trained on large amounts of text, allowing them to generate natural language responses that include idioms or language variations. - Reasoning capabilities: LLMs have some reasoning capabilities, which make it possible for them to compare facts or draw conclusions. ## Challenges RAG QA systems also have limitations that are important to consider: - **Cost:** Proprietary LLMs often come with a price tag. The pricing models are based on the number of tokens processed or per query. - **Limited context length:** Models have a maximum token limit they can handle. This includes both the prompt and the generated output. When handling long documents, the model may truncate the generated text to fit within the allowed context length. - **Factual accuracy:** Models may generate fictional or incorrect outputs with a high level of confidence. This is known as hallucinations. Hallucinations can occur because of biases in training data or the model's inability to differentiate between factual and fictional information. - **Latency:** Generative QA systems are generally slower compared to extractive QA systems. - **Output control:** LLMs can sometimes generate harmful, inappropriate, or biased content. - **Evaluation:** Evaluating generative models remains challenging. Some of the reasons for that include a lack of objective metrics. Evaluation often involves subjective human judgment, and the diverse outputs make establishing a single ground truth difficult. ## Generative QA on Your Data To mitigate concerns about hallucinations and unreliable answers, you can run a generative QA system on your own data using a retrieval-augmented generation (RAG) approach. This involves limiting the context to a predefined set of documents and adding a `Retriever` component to your QA system. In , you can pass your documents in the prompt. When given a query, the Retriever finds the most relevant documents, injects them into the prompt, and passes them on to the generative model. The model uses these documents to produce the final answer. To ensure the generated answers are based on the documents you feed to the model, instruct the LLM to add references to the answer text so that you can verify it's grounded in your data. This helps build a reliable system that users can trust. For details, see [Enable References](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx). ## Applications RAG QA systems excel in scenarios where you need novel, natural-language answers and not verbatim from existing documents. Some popular applications include: - Chatbots, AI assistants, and customer support applications offering personalized assistance across various questions. - Writing aids and content generation apps automating content creation tasks and assisting with content curation. - Learning assistants in educational applications, providing explanations and summaries of content. - Translation aids. ## RAG in RAG pipelines in : - Are search systems that generate novel answers based on your data or the model's knowledge of the world, depending on the setup. - Can work on your own data (retrieval-augmented generation). You can pass the documents in the prompt and filter them with a `Retriever`. - Can be chat-based. There is a RAG-Chat pipeline template that you can use out of the box and then test in Playground. supports you throughout the process of creating a generative QA system by: - Providing pipeline templates, ready to use. - Providing [Prompt Explorer](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx), which is a sandbox environment for prompt engineering. - Offering a library of tested and curated prompts you can reuse and modify as needed. provides templates with models by OpenAI, Claude by Anthropic, Command by Cohere, and more. But even if you choose a template with a specific model, you can then easily swap it for another one by choosing a different model in the component settings. --- ## Large Language Models Overview Choosing the right LLM for your task is a challenge. This overview summarizes all currently available LLMs and their capabilities. *** ## LLM Introduction There are numerous LLMs on the market that can process and generate human-like content. They range from paid versions to open source alternatives. While all these models were trained to perform similar core tasks, their proficiency varies, making some of them better at particular tasks than others. Identifying the optimal LLM for your needs involves thorough testing and comparative analysis based on your use case. This overview is meant to give you an idea of what LLMs are available and help you choose the ones to explore further. ## Tasks All LLMs currently available on the market can perform the following tasks: - text generation (this includes both creative and to-the-point text) - code generation - translation - acting as AI assistants and chatbots Some LLMs are better at some of these tasks than others. The differences may lie in the level of nuance the LLM can understand, the speed, or the languages it can operate in. ## Models Within a Family Large language models (LLMs) come in families. For example, GPT is a family that includes several models. Within a family, models can vary in size, context window (the number of tokens they can process), and the type of instructions they handle (such as instruct and chat models). - Larger models usually deliver better performance but run more slowly. - Models with larger context windows are more expensive but can process more text in a single request. ## Model Types ### Instruct Models These models are trained to follow direct instructions or prompts. They're optimized for task completion rather than free-flowing conversations. They work well with specific commands and instructions. These models often include the word "instruct" in their name. Instruct models follow a prompt and output a string. They're best for: - Text transformation and summarization - Question answering and information retrieval - Generating content based on prompts - Task-specific assistance Examples: OpenAI's InstructGPT or Meta's LlaMA ### Chat Models Chat models are optimized for open-ended conversations and generating responses based on prior context in a chat-based format. Unlike instruct models, they process multiple exchanges, preserving context across turns to maintain a coherent dialogue. These models take in a list of messages, where each message has a role (such as system, user, or assistant) and content. The system message helps set the conversation's overall tone and instructions. The model then generates the next message in the conversation, usually as the assistant. #### Tool Calling Chat models can also interact with external tools or functions. To do this, you provide a tool configuration, and the model generates a JSON schema that can be used to call the tool or function. They're best for: - Participating in multi-turn conversations and maintaining the dialogue format - Systems where you need to call external tools or functions Examples: Anthropic's Clause, OpenAI's ChatGPT ## Models Overview As the field is rapidly developing and new models with enhanced capabilities keep being released, we recommend checking the following model providers resources to learn about their latest models: - [Anthropic](https://www.anthropic.com/) - [Cohere](https://cohere.com/command) - [DeepSeek](https://www.deepseek.com/) - [Google DeepMind](https://deepmind.google/technologies/gemini/) - [Meta](https://www.llama.com/docs/model-cards-and-prompt-formats/) - [Mistral](https://docs.mistral.ai/getting-started/models/models_overview/) - [OpenAI](https://openai.com/index/hello-gpt-4o/) --- ## Model Context Protocol(Learn) Learn what the Model Context Protocol (MCP) is, how it works, and how it can improve your workflows. ## What is the Model Context Protocol? The Model Context Protocol (MCP) is a way to let AI systems, like LLMs, connect to the outside world. With MCP, AI can access newest information, trigger actions, or interact with other systems. Instead of building a custom connection for every app, database, or API, MCP provides a universal way to do this. MCP acts like a universal adapter. It defines a common protocol, or a standard, for how AI applications communicate with external tools and data sources. Just as USB-C standardizes how devices connect, MCP standardizes how AI connects to external capabilities. For , this means you can connect pipelines to a wide range of tools and services with the same interface. MCP defines how an AI assistant requests data from tools and how those tools respond. When a tool supports MCP, you can use it across any compatible client, such as Cursor, Claude Desktop, or your own custom agent. ## Key Concepts MCP uses a client-server architecture with three key components: - **MCP Host**: The AI app the user interacts with, like Claude Desktop or VS Code. The host manages the overall workflow and launches one MCP client for each server it connects to. - **MCP Client**: The component that manages communication between the host and the server. - **MCP Server**: A program that offers capabilities, like tools, resources, or prompts, to the client or host. It can run locally or remotely. The host coordinates the entire process. It creates one MCP client to communicate with each MCP server. ### The Workflow Here's how a typical interaction works: If the host is Claude Desktop with an MCP extension, and a user asks a question that requires an external tool, the host forwards the query to its MCP client. The client starts a session with the MCP server. They exchange information about available tools and capabilities. The client sends a tool call, the server returns the result, and the client passes the response back to the host. The host then formats it into natural language for the user. ## Benefits of MCP MCP brings several key benefits to your AI applications. ### Vendor-Agnostic Integration MCP abstracts away vendor-specific APIs, making it possible to connect to external tools and services without writing custom integration code. MCP handles the communication protocol, so you focus on building your AI logic. ### Flexible Tool Access Access a growing ecosystem of MCP-compatible tools, including: - Database connections - Web search capabilities - File system operations - API integrations - Custom business tools ### Enhanced AI Capabilities Give your AI models access to real-time data and tools, enabling them to: - Answer questions with current information - Perform actions on external systems - Access specialized data sources - Execute complex workflows ### Future-Proof Architecture As more tools adopt MCP, your pipelines automatically gain access to new capabilities without code changes. --- ## Language Models With such a variety of readily available fine-tuned models, it's difficult to choose the best one for your use case. This guide tells you about different types of models and when to use them. *** ## What Are Language Models? Language models are neural networks trained on large amounts of text to learn how a language works. If you think about the way you're using your native tongue, you'll observe that it's intuitive. You don't have to think about grammar rules when speaking; you just know and apply them intuitively. A language model attempts to enable machines to use language in a similar way humans do. Language models are no magic. The way a model works is that it decides how probable it is that a word is valid in a particular word sequence. By _valid_, we mean that it resembles the way humans talk, not that it complies with any grammar rules. The latest advance in NLP is the transformer architecture which led to top-performing models, such as BERT. It differs from previously used architectures in that instead of processing passages of text word-by-word, transformer-based models can process whole sentences at once, which makes them much faster in training but also in inference. They can also learn the relations between different words in a sentence and how these relations affect the expected model output—a functionality called attention mechanism. ### Fine-Tuned Models A fine-tuned model is a language model trained on a large amount of raw text to perform a specific NLP task, such as text classification or question answering. A lot of fine-tuned models are publicly available for free on model hubs such as [Hugging Face](https://huggingface.co/models). You can just grab them from there and use them in your NLP app as a starting point. You no longer need to train your own model, which takes a lot of time and a lot of data and uses a lot of computer resources. ### Large Language Models (LLMs) Large language models (LLMs) are huge models trained on enormous amounts of data. Interacting with such a model resembles talking to another person. These models have general knowledge of the world. You can ask them almost anything, and they'll be able to answer. LLMs are trained to perform many NLP tasks with little training data. Some examples of tasks they can handle are language translation, summarization, question answering, or text generation. These models are called "large" because they are trained on a large dataset, typically consisting of millions of words. Also, their architecture is much more complicated than the architecture of regular models. It consists of hundreds of layers and millions of parameters. This makes these models take up a lot of computational resources to run. During the training, these models are not explicitly given task-specific labels or examples to learn from. Instead, they learn by predicting the next word in a sequence of words based on the context. During training, they memorize a lot of the training data. That's where their knowledge comes from. LLMs have their limitations as well. Their knowledge isn't updated, so they won't be able to answer questions about very recent events or questions where the answer changes over time. They'll answer with something that was correct in the past. An example question like that is "Who's the president of the USA?". Some of the most well-known LLMs include GPT-4, Anthropic's Claude or Sonnet, Mistral, or LLaMA 2. For an overview of the models, see [Large Language Models Overview](/docs/learn/large-language-models-overview.mdx). #### Model Parameters When interacting with large language models, take into account these three parameters as they can significantly impact your prompt performance: - `temperature` The lower the temperature, the more realistic the results. For fact-based question answering, we recommend setting the temperature to lower values, like 0. A higher temperature can lead to more random, creative, and diverse answers. You may consider setting the temperature to a higher value if you want the model to perform creative tasks, like poem generation. - `top_p` This parameter controls nucleus sampling, which is a technique to generate text that balances both coherence and diversity. It limits the set of possible next words (the nucleus) based on the threshold of probability value _p._ You typically set it to a value between 0 and 1. If you want the model to generate factual answers, set top_p to a low value, like 0. - `stop_words` When the model generates the set of characters specified as the stop words, it stops generating more text. It helps to control the length and relevance of the generated text. See also [Prompt Engineering Guidelines](./prompt-engineering-guidelines.mdx). ### Model Naming Conventions If you're new to models, it's helpful to understand the model naming convention as the name already gives you a hint about what the model can do. The first part of the name is the user that trained and uploaded the model. Then, there is the architecture that the model uses and the size of the model. The last part of the name is the dataset used to train the model. Here's a typical model name: `deepset/roberta-base-squad2` `deepset` is the user who trained and uploaded the model, `roberta` is the model architecture, `base` is the size, and `squad2` is the dataset on which the model was trained. #### Model Types You don't need to have in-depth knowledge of its architecture to use a model, but it's helpful to have a rough overview of the most common model types out there and their key differences. This will help you to better understand which models to try out in your own pipeline. Here's a timeline showing when the most common model architectures were developed. To get an idea of how different model types perform, have a look at [Reader Performance Benchmarks](https://haystack.deepset.ai/benchmarks/latest). For recommended models, see [Models in ](/docs/concepts/language-models-in-deepset-cloud.mdx). #### Model Size Large models have better accuracy, but this comes at the cost of speed and the resources needed to run them. Large models can be significantly slower than smaller ones, using up a lot of your graphic card memory or even exceeding its limit. Distilled models are a good compromise, as they preserve accuracy similar to the larger models but are much smaller and easier to deploy. #### Training Dataset Standard datasets are used when training a model for a particular task. For example, SQuAD stands for Stanford Question Answering Dataset and is the standard dataset for training English-language models for question answering. :::tip Checking Models for Datasets When searching for a model for your task, you can check what dataset is typically used for it and then search for a model that was trained on this dataset. ::: --- ## Prompt Engineering Guidelines Prompts are instructions for large language models to generate a response or complete a task. The way you construct your prompt impacts the accuracy and format of the answer the model returns. That's why it's important to get your prompts right. This guide contains guidelines and best practices for writing prompts in . *** ## General Tips - Prompts can contain instructions or questions to pass to the model. They can also contain additional information, such as context or examples. - Prompt engineering is an iterative process, and it's rare to craft the perfect prompt on your first attempt. Be prepared to experiment and refine as you go. Writing effective prompts comes down to practice and learning through trial and error. - Version your prompts to compare the performance of different versions and choose the one that worked best. - Start with simple, zero-s hot prompts and then keep making them more complex to reach the required accuracy of answers. You can add more context and examples to each iteration of your prompt. If you're not seeing any improvements, fine-tune the model. - Always use the latest models available. - The way you write prompts is often specific to the model you're using. Always check the instructions to prompt that particular model. ## Prompt Structure Remember that the prompt's structure depends on the task you want the model to perform. Experiment and test what works best. Prompts with a structure that follows these guidelines seem to achieve better results than prompts with a random structure: - The prompt has instructions, context, input data, and output format. Not all these components are necessary, and they may vary depending on the model's task. - You can try experimenting with specific prompt structures, for example: ``` Question: Context: Answer: ``` or for question answering without a given context: ``` Q: A: ``` ### Instructions - Put them at the beginning of the prompt. - Use commands such as "write," "summarize," and "translate." Try using different keywords and see which yields the best results. - Separate instructions from the context with a delimiter, such as quotation marks ("") or hashes (###). - Separate the instructions, examples, context, and input data with one or more line breaks. Examples: ``` ### Instruction ### Give a title to the article. The title must have 5 words. Article: Online retail giant Amazon has said it plans to shutdown three warehouses in the UK putting 1200 jobs at risk. Title: ``` ``` Instructions: Detect the language of the text. Answer with the name of the language. Text: Professionelle Beratung und ein Top-Service sind für uns selbstverständlich. Daher bringen unsere Mitarbeiter eine große Portion Kompetenz und Erfahrung mit. ``` ### Context - Specify any information you want the model to use to generate the answer. The context should help the model arrive at better responses. - In RAG pipelines, you can pass documents as context for the model. Example: ``` Answer the question using the context. If you are not sure about the answer, answer with "I don't know". Context: Contrails are a manmade type of cirrus cloud formed when water vapor from the exhaust of a jet engine condenses on particles, which come from either the surrounding air or the exhaust itself, and freezes, leaving behind a visible trail. The exhaust can also trigger the formation of cirrus by providing ice nuclei when there is an insufficient naturally-occurring supply in the atmosphere. One of the environmental impacts of aviation is that persistent contrails can form into large mats of cirrus, and increased air traffic has been implicated as one possible cause of the increasing frequency and amount of cirrus in Earth's atmosphere. Question: Why do airplanes leave contrails in the sky? ``` In , you can include the documents in the prompt: ```text You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: ``` ### Output Format - Be specific about the format you want the model to use for the answer. If needed, specify the length, style, and so on. - It may help to give the model a couple of concrete examples. Example: ``` Classify the text into neutral, negative, or positive. Text: I love Berlin! Answer: ``` By giving the model examples, you're showing exactly what answer you expect. ### Language - Be direct, specific, and detailed. - Be concise, as there's usually a limit on the number of tokens in a prompt and longer prompts are computationally more expensive than shorter ones. - Focus on what you want the model to do rather than what you don't want it to do. Example: ```Text Using specific language Explain the concept nuclear sampling in 3 to 5 sentences to a 10-year old. ``` ```Text Using imprecise language Explain nuclear sampling. Be short and don't use too complicated language. ``` ## Role Prompting Role prompting is a technique for instructing the AI to assume a specific role or persona or act in a certain way. It's helpful to control the style, tone, and even the level of detail of the model's answers. Example: In this example, we want the AI to sound professional and generate objective, to-the-point answers: ```text You are a technical expert. You answer questions truthfully based on provided documents. ``` When asking the AI to write an email, prompting it to assume the role of a customer service representative may result in a more relational and solution-oriented answer: ``` You are a customer service representative. Write an email to a client advising them about a delay in the delivery schedule due to logistical problems. ``` ## Few-Shot Prompts Few-shot prompts contain a couple of examples for the model. By giving the model examples, you demonstrate what you expect it to do and enable it to perform in-context learning to improve its performance. Few-shot prompting helps to express ideas that may be difficult to explain through instruction. It can also significantly improve the accuracy of the model's answers. Use few-shot prompts if you require the model to return an answer in a specific format or if a simple prompt didn't yield the results you needed. - Use consistent formatting. - Provide examples in random order. For example, don't put all negative examples first and positive ones second. Mix them up as the order might bias the model. - Make sure you use labels. Usually, the more examples you provide, the better, but be aware of the model's context window size limitations. Examples: This example is from the [Brown et al. 2020](https://arxiv.org/abs/2005.14165) paper: ``` A "whatpu" is a small, furry animal native to Tanzania. An example of a sentence that uses the word whatpu is: We were traveling in Africa and we saw these very cute whatpus. To do a "farduddle" means to jump up and down really fast. An example of a sentence that uses the word farduddle is: ``` Model answer: ``` One day when I was playing tag with my little sister, she got really excited and she started doing these crazy farduddles. ``` Or for sentiment analysis: ``` Classify the text into neutral, negative, or positive. Text: I love Berlin! Answer: positive Text: I hate Paris. Answer: negative Text: I've never been to Bangalore. Answer: neutral Text: I don't like Tokio. Answer: ``` --- ## Agent Add reasoning and external tools to your pipelines through the `Agent` component. An `Agent` can understand different types of input, decide when to take action, and use tools and memory to complete tasks. It generates context-aware responses based on its reasoning. You can think of an `Agent` as a coordinator for your pipeline. It manages the flow of a conversation and determines which tools to use and when to use them. Under the hood, it relies on an LLM to plan and execute these steps. ## Key Features The `Agent` component: - Works with different language models. - Can use external tools including entire pipelines, custom functions, and MCP servers. - Lets you define custom exit conditions to control when the `Agent` stops. For example, stop after it generates a response or uses a specific tool. - Supports Jinja2 templating in both the system prompt and user prompt for dynamic, context-aware behavior at runtime. - Maintains conversation history. - Allows real-time streaming responses for both synchronous and asynchronous mode. - Supports asynchronous execution. - Stores memory in its state, including tool calls and conversation history. - Has tracing support. Connect a tracer like Langfuse or Weights & Biases Weave to monitor the `Agent`'s execution in depth. ## How It Works 1. The Agent receives a user message. 2. It sends the message to its chat model, along with the list of available tools. 3. The model decides whether to respond directly or call a tool. It returns either a text response or a tool call. - If the model returns text, the Agent returns the response along with the updated conversation. - If the model returns a tool call: 1. The Agent calls the tool and collects the result. 2. If configured, the Agent stores selected tool outputs in its state. You define which outputs to store. 3. The Agent adds the result to the conversation history. 4. The Agent then evaluates whether to stop or continue: - If the tool name matches an item in `exit_conditions` and the tool runs successfully, the Agent stops and returns the conversation. - If the tool returns an error, the Agent continues and sends the error message back to the LLM. - If the tool doesn't match any `exit_conditions`, the Agent continues. 5. When continuing, the Agent sends the updated conversation back to the model. The model can respond or call additional tools. This loop continues until one of the following conditions occurs: - An `exit_condition` is met. - The `max_agent_steps` limit is reached. ### Agent Without Tools When you use an Agent without providing tools, it behaves like the `LLM` component: - It produces one response from the LLM - It immediately exits after generating text - It cannot perform iterative reasoning or tool calling We recommend using the `LLM` component instead of the `Agent` component when you don't need to use tools. ## Configuration 1. Drag the `Agent` component onto the canvas from the Component Library. 2. Click **Model** on the component card to open the configuration panel. 3. On the **General** tab: 1. Choose a model from the list. Make sure is connected to the model provider. For help, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). :::tip Custom Models You can use custom model definitions to configure the Agent's model. For details, see [Add Custom Model Definitions](/docs/how-to-guides/managing-access/add-custom-model-definitions.mdx). ::: 2. Optionally, add a system prompt to provide fixed instructions that guide the Agent's behavior, tone, or knowledge throughout the conversation. The system prompt supports dynamic content through Jinja2 syntax. 3. Optionally, add a user prompt with a reusable Jinja2 template. This lets you invoke the Agent with dynamic variables without manually constructing `ChatMessage` objects. When you combine `messages` with `user_prompt`, the rendered user prompt is appended to the provided messages. Use `required_variables` to specify which template variables must be provided. For detailed instructions on writing prompts and adding dynamic content to system prompts, see [Writing Prompts in ](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). :::tip Jinja in the `Agent` component When you add or edit the user prompt for the `Agent` component, you write regular text. To insert a variable, type **`@`** and a list of available variables appears so you can pick one. To insert a function, type **`/`** and you see all functions you can add to the template. To see the raw Jinja2 syntax, enable the **Jinja** toggle. It's disabled by default. ::: 4. If needed, add tools to the Agent: 1. Click **Add tool** in the Tools section. 2. Choose the tool type from the list. 3. Follow the instructions to configure the tool. If you need help, see [Configure an Agent](/docs/how-to-guides/building-agents/configuring-agent.mdx). 5. Go to the **Advanced** tab to configure model-specific settings and agent-specific settings. Model-specific parameters depend on the model you chose. Agent-specific settings include: - `Max agent steps` to limit the number of actions the Agent can perform. For more complicated tasks, you may need to increase this value. Note that increasing this value may increase the cost and time of the task. - `Exit conditions` to define when the Agent stops. The Agent runs iteratively, calling tools and feeding their outputs back to the model until one of the exit conditions is met. - To stop the Agent when it generates a text response, choose `text`. - To stop the Agent after it uses a specific tool, choose the tool's name from the list. - You can choose multiple exit conditions and the Agent stops when any of the conditions is met. For example, to stop the Agent when it generates a text response or after a specific tool is used, choose `text` and the tool's name. - `Retry on tool failure` to automatically retry the Agent if a tool call fails. This is useful if the tool call times out or temporarily fails. For guidance on how to configure the Agent, see [Building AI Agents](/docs/how-to-guides/building-agents/building-ai-agents.mdx). For an explanation of the Agent and its tools, see also [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx) and [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx). ## Connections The `Agent`'s input connections depend on the variables you configure in the user and system prompts. If you use the same variable in both prompts, it's shown as a single input connection. The Agent accepts an optional list of `ChatMessage` objects through its `messages` input. If you don't provide messages, you must have a `user_prompt` or `system_prompt` configured. Output connections depend on the selected tools and which of their outputs are stored in the Agent state. Only outputs saved to the state appear as output connections. By default, the Agent outputs a single `ChatMessage` through its `last_message` output and a list of `ChatMessage` objects through its `messages` output. The `messages` output is a concatenated system prompt, messages provided as input, user prompt (if provided), and the Agent's answer appended at the end. :::tip Last Message vs Messages If `Agent` is the component that produces the final output of your pipeline, you typically use the `last_message` output. If you need the full conversation history, use the `messages` output. You can connect `last_message` to the `Output` component's `messages` input to display the final answer. ::: You can pass messages to the `Agent` directly from the `Input` component. Add `messages` as the `Input`'s parameter and connect the `Input`'s `messages` output to the `Agent`'s `messages` input. The messages contain the query and the conversation history. You can send the `Agent`'s `last_message` output to the `Output` component to get the final answer. Configure `messages` as the `Output`'s parameter and connect the `Agent`'s `last_message` output to the `Output`'s `messages` input. You can also send its `messages` output to another component. ## Source Code To check this component's source code, open [`agent.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/agents/agent.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: |- {% message role="system" %} You are a helpful assistant. Answer user's question. {% endmessage %} max_agent_steps: 100 raise_on_tool_invocation_failure: false ``` ### Basic Agent Configuration without Tools This is the basic Agent configuration, with a model, system prompt, and user prompt. The user prompt includes a query that's dynamically inserted into the prompt when the Agent runs. There are no tools configured. ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: system_prompt: |- {% message role="system" %} You are a helpful assistant. Answer user's question. {% endmessage %} user_prompt: required_variables: exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: ``` ### Dynamic System Prompt with Jinja2 The Agent's `system_prompt` supports Jinja2 message template syntax, which lets you inject runtime variables and conditional logic directly into the system prompt. This is useful for adapting the Agent's behavior dynamically, for example, changing the response language, tone, or injecting time-aware instructions. To use Jinja2 in the system prompt, wrap the prompt content in `{% message role="system" %}...{% endmessage %}` tags and use `{{ variable_name }}` for variables. List the variable names in `required_variables` to make them mandatory inputs. ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: system_prompt: >- {% message role="system" %} You are a helpful assistant. Always respond in {{ language }}. Today's date is {{ current_date }}. {% endmessage %} user_prompt: "{{ query }}" required_variables: - language - current_date - query exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false ``` In this example, the `language` and `current_date` variables are injected into the system prompt at runtime. You can pass these as pipeline inputs or connect them to other components in the pipeline. ### Basic Agent Configuration with Tools This is the basic Agent configuration, with a model, system prompt, user prompt, and tools: an MCP server and a search pipeline. ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: customer_suport_triage_agent description: Use this tool to review customer tickets and get their details. input_mapping: query: - ticket_fetcher.query messages: - agent.messages output_mapping: agent.messages: messages pipeline: components: ticket_fetcher: type: deepset_cloud_custom_nodes.code.code_component.Code init_parameters: code: >- from datetime import datetime, timedelta from haystack import component @component class Code: """Fetches ticket details by ID. Replace with your ticketing API or database.""" @component.output_types( ticket_submitted_at=str, customer_tier=str, customer_name=str, ticket_content=str, ) def run(self, query: str) -> dict: ticket_id = query.strip() now = datetime.utcnow() submitted = now - timedelta(hours=2) return { "ticket_submitted_at": submitted.strftime("%Y-%m-%d %H:%M UTC"), "customer_tier": "Premium", "customer_name": "Acme Corp", "ticket_content": f"[Ticket {ticket_id}] Login fails with 502 after password reset. User needs access restored urgently.", } agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false system_prompt: >- You are a customer support triage specialist. Your job is to: 1. Analyze incoming support tickets. 2. Classify their urgency (critical, high, medium, low). 3. Check if the ticket breaches SLA based on the submission time and today's date. 4. Draft a professional first response to the customer. SLA rules: - Critical: respond within 1 hour - High: respond within 4 hours - Medium: respond within 24 hours - Low: respond within 72 hours Always be empathetic and solution-oriented. max_agent_steps: 5 user_prompt: >- Today's date and time: {% now 'utc'%} Ticket submitted: {{ ticket_submitted_at }} Customer tier: {{ customer_tier }} Customer name: {{ customer_name }} {{ ticket_content }} Based on the SLA rules and the time elapsed since submission, classify urgency and draft a response. required_variables: - ticket_submitted_at - customer_tier - customer_name - ticket_content connections: - sender: ticket_fetcher.ticket_submitted_at receiver: agent.ticket_submitted_at - sender: ticket_fetcher.customer_tier receiver: agent.customer_tier - sender: ticket_fetcher.customer_name receiver: agent.customer_name - sender: ticket_fetcher.ticket_content receiver: agent.ticket_content max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: messages: source: messages outputs_to_state: {} parameters: description: "A component that combines: 'ticket_fetcher': Forward all inputs to the wrapped component's run method., 'agent': Process messages and execute tools until an exit condition is met." properties: query: description: "Provided to the 'answer_builder' component as: 'The query used in the prompts for the Generator.'." type: string messages: description: "Provided to the 'agent' component as: 'List of Haystack ChatMessage objects to process.'." items: $ref: "#/$defs/ChatMessage" type: array required: - query - messages type: object $defs: ChatMessage: properties: role: $ref: "#/$defs/ChatRole" description: Field 'role' of 'ChatMessage'. content: description: Field 'content' of 'ChatMessage'. items: anyOf: - $ref: "#/$defs/TextContent" - $ref: "#/$defs/ToolCall" - $ref: "#/$defs/ToolCallResult" - $ref: "#/$defs/ImageContent" - $ref: "#/$defs/ReasoningContent" - $ref: "#/$defs/FileContent" type: array name: anyOf: - type: string - type: "null" default: description: Field 'name' of 'ChatMessage'. meta: additionalProperties: true default: {} description: Field 'meta' of 'ChatMessage'. type: object required: - role - content type: object ChatRole: description: Enumeration representing the roles within a chat. enum: - user - system - assistant - tool type: string FileContent: properties: base64_data: description: A base64 string representing the file. type: string mime_type: anyOf: - type: string - type: "null" default: description: >- The MIME type of the file (e.g. "application/pdf"). Providing this value is recommended, as most LLM providers require it. If not provided, the MIME type is guessed from the base64 string, which can be slow and not always reliable. filename: anyOf: - type: string - type: "null" default: description: Optional filename of the file. Some LLM providers use this information. extra: additionalProperties: true default: {} description: >- Dictionary of extra information about the file. Can be used to store provider-specific information. To avoid serialization issues, values should be JSON serializable. type: object validation: default: true description: >- If True (default), a validation process is performed: - Check whether the base64 string is valid; - Guess the MIME type if not provided. Set to False to skip validation and speed up initialization. type: boolean required: - base64_data type: object ImageContent: properties: base64_image: description: A base64 string representing the image. type: string mime_type: anyOf: - type: string - type: "null" default: description: >- The MIME type of the image (e.g. "image/png", "image/jpeg"). Providing this value is recommended, as most LLM providers require it. If not provided, the MIME type is guessed from the base64 string, which can be slow and not always reliable. detail: anyOf: - enum: - auto - high - low type: string - type: "null" default: description: Optional detail level of the image (only supported by OpenAI). One of "auto", "high", or "low". meta: additionalProperties: true default: {} description: Optional metadata for the image. type: object validation: default: true description: >- If True (default), a validation process is performed: - Check whether the base64 string is valid; - Guess the MIME type if not provided; - Check if the MIME type is a valid image MIME type. Set to False to skip validation and speed up initialization. type: boolean required: - base64_image type: object ReasoningContent: properties: reasoning_text: description: The reasoning text produced by the model. type: string extra: additionalProperties: true default: {} description: >- Dictionary of extra information about the reasoning content. Use to store provider-specific information. To avoid serialization issues, values should be JSON serializable. type: object required: - reasoning_text type: object TextContent: properties: text: description: The text content of the message. type: string required: - text type: object ToolCall: properties: tool_name: description: The name of the Tool to call. type: string arguments: additionalProperties: true description: The arguments to call the Tool with. type: object id: anyOf: - type: string - type: "null" default: description: The ID of the Tool call. extra: anyOf: - additionalProperties: true type: object - type: "null" default: description: >- Dictionary of extra information about the Tool call. Use to store provider-specific information. To avoid serialization issues, values should be JSON serializable. required: - tool_name - arguments type: object ToolCallResult: properties: result: anyOf: - type: string - items: anyOf: - $ref: "#/$defs/TextContent" - $ref: "#/$defs/ImageContent" type: array description: The result of the Tool invocation. origin: $ref: "#/$defs/ToolCall" description: The Tool call that produced this result. error: description: Whether the Tool invocation resulted in an error. type: boolean required: - result - origin - error type: object _meta: name: customer_suport_triage_agent description: Use this tool to review customer tickets and get their details. tool_id: - type: haystack_integrations.tools.mcp.MCPToolset data: server_info: type: haystack_integrations.tools.mcp.mcp_tool.StreamableHttpServerInfo url: https://api.githubcopilot.com/mcp/ timeout: 900 token: type: env_var strict: true env_vars: - GITHUB_MCP_TOKEN_83168973 tool_names: - add_comment_to_pending_review - add_issue_comment - add_reply_to_pull_request_comment - assign_copilot_to_issue - create_branch - create_or_update_file - create_pull_request - create_pull_request_with_copilot - create_repository - delete_file - fork_repository - get_commit - get_copilot_job_status - get_file_contents - get_label - get_latest_release - get_me - get_release_by_tag - get_tag - get_team_members - get_teams - issue_read - issue_write - list_branches - list_commits - list_issue_types - list_issues - list_pull_requests - list_releases - list_tags - merge_pull_request - pull_request_read - pull_request_review_write - push_files - request_copilot_review - run_secret_scanning - search_code - search_issues - search_pull_requests - search_repositories - search_users - sub_issue_write - update_pull_request - update_pull_request_branch eager_connect: false _meta: name: Github description: tool_id: system_prompt: >- {% message role="system" %} You are a helpful assistant. Answer user's questions in a polite and professional manner. Use customer_support_triage_agent to get the details of the customer and the problem they have. Use Github to browse the repository for similar issues and their reso {% endmessage %} user_prompt: "Question: {{ query }}" required_variables: - query exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: ``` ### Agent In a Pipeline This is an Agent with Github MCP and a local search pipeline as tools used in a pipeline: And here's the YAML configuration: ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: customer_suport_triage_agent description: Use this tool to review customer tickets and get their details. input_mapping: query: - ticket_fetcher.query messages: - agent.messages output_mapping: agent.messages: messages pipeline: components: ticket_fetcher: type: deepset_cloud_custom_nodes.code.code_component.Code init_parameters: code: >- from datetime import datetime, timedelta from haystack import component @component class Code: """Fetches ticket details by ID. Replace with your ticketing API or database.""" @component.output_types( ticket_submitted_at=str, customer_tier=str, customer_name=str, ticket_content=str, ) def run(self, query: str) -> dict: ticket_id = query.strip() now = datetime.utcnow() submitted = now - timedelta(hours=2) return { "ticket_submitted_at": submitted.strftime("%Y-%m-%d %H:%M UTC"), "customer_tier": "Premium", "customer_name": "Acme Corp", "ticket_content": f"[Ticket {ticket_id}] Login fails with 502 after password reset. User needs access restored urgently.", } agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false system_prompt: >- You are a customer support triage specialist. Your job is to: 1. Analyze incoming support tickets. 2. Classify their urgency (critical, high, medium, low). 3. Check if the ticket breaches SLA based on the submission time and today's date. 4. Draft a professional first response to the customer. SLA rules: - Critical: respond within 1 hour - High: respond within 4 hours - Medium: respond within 24 hours - Low: respond within 72 hours Always be empathetic and solution-oriented. max_agent_steps: 5 user_prompt: >- Today's date and time: {% now 'utc'%} Ticket submitted: {{ ticket_submitted_at }} Customer tier: {{ customer_tier }} Customer name: {{ customer_name }} {{ ticket_content }} Based on the SLA rules and the time elapsed since submission, classify urgency and draft a response. required_variables: - ticket_submitted_at - customer_tier - customer_name - ticket_content connections: - sender: ticket_fetcher.ticket_submitted_at receiver: agent.ticket_submitted_at - sender: ticket_fetcher.customer_tier receiver: agent.customer_tier - sender: ticket_fetcher.customer_name receiver: agent.customer_name - sender: ticket_fetcher.ticket_content receiver: agent.ticket_content max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: messages: source: messages outputs_to_state: {} parameters: description: "A component that combines: 'ticket_fetcher': Forward all inputs to the wrapped component's run method., 'agent': Process messages and execute tools until an exit condition is met." properties: query: description: "Provided to the 'answer_builder' component as: 'The query used in the prompts for the Generator.'." type: string messages: description: "Provided to the 'agent' component as: 'List of Haystack ChatMessage objects to process.'." items: $ref: "#/$defs/ChatMessage" type: array required: - query - messages type: object $defs: ChatMessage: properties: role: $ref: "#/$defs/ChatRole" description: Field 'role' of 'ChatMessage'. content: description: Field 'content' of 'ChatMessage'. items: anyOf: - $ref: "#/$defs/TextContent" - $ref: "#/$defs/ToolCall" - $ref: "#/$defs/ToolCallResult" - $ref: "#/$defs/ImageContent" - $ref: "#/$defs/ReasoningContent" - $ref: "#/$defs/FileContent" type: array name: anyOf: - type: string - type: "null" default: description: Field 'name' of 'ChatMessage'. meta: additionalProperties: true default: {} description: Field 'meta' of 'ChatMessage'. type: object required: - role - content type: object ChatRole: description: Enumeration representing the roles within a chat. enum: - user - system - assistant - tool type: string FileContent: properties: base64_data: description: A base64 string representing the file. type: string mime_type: anyOf: - type: string - type: "null" default: description: >- The MIME type of the file (e.g. "application/pdf"). Providing this value is recommended, as most LLM providers require it. If not provided, the MIME type is guessed from the base64 string, which can be slow and not always reliable. filename: anyOf: - type: string - type: "null" default: description: Optional filename of the file. Some LLM providers use this information. extra: additionalProperties: true default: {} description: >- Dictionary of extra information about the file. Can be used to store provider-specific information. To avoid serialization issues, values should be JSON serializable. type: object validation: default: true description: >- If True (default), a validation process is performed: - Check whether the base64 string is valid; - Guess the MIME type if not provided. Set to False to skip validation and speed up initialization. type: boolean required: - base64_data type: object ImageContent: properties: base64_image: description: A base64 string representing the image. type: string mime_type: anyOf: - type: string - type: "null" default: description: >- The MIME type of the image (e.g. "image/png", "image/jpeg"). Providing this value is recommended, as most LLM providers require it. If not provided, the MIME type is guessed from the base64 string, which can be slow and not always reliable. detail: anyOf: - enum: - auto - high - low type: string - type: "null" default: description: Optional detail level of the image (only supported by OpenAI). One of "auto", "high", or "low". meta: additionalProperties: true default: {} description: Optional metadata for the image. type: object validation: default: true description: >- If True (default), a validation process is performed: - Check whether the base64 string is valid; - Guess the MIME type if not provided; - Check if the MIME type is a valid image MIME type. Set to False to skip validation and speed up initialization. type: boolean required: - base64_image type: object ReasoningContent: properties: reasoning_text: description: The reasoning text produced by the model. type: string extra: additionalProperties: true default: {} description: >- Dictionary of extra information about the reasoning content. Use to store provider-specific information. To avoid serialization issues, values should be JSON serializable. type: object required: - reasoning_text type: object TextContent: properties: text: description: The text content of the message. type: string required: - text type: object ToolCall: properties: tool_name: description: The name of the Tool to call. type: string arguments: additionalProperties: true description: The arguments to call the Tool with. type: object id: anyOf: - type: string - type: "null" default: description: The ID of the Tool call. extra: anyOf: - additionalProperties: true type: object - type: "null" default: description: >- Dictionary of extra information about the Tool call. Use to store provider-specific information. To avoid serialization issues, values should be JSON serializable. required: - tool_name - arguments type: object ToolCallResult: properties: result: anyOf: - type: string - items: anyOf: - $ref: "#/$defs/TextContent" - $ref: "#/$defs/ImageContent" type: array description: The result of the Tool invocation. origin: $ref: "#/$defs/ToolCall" description: The Tool call that produced this result. error: description: Whether the Tool invocation resulted in an error. type: boolean required: - result - origin - error type: object _meta: name: customer_suport_triage_agent description: Use this tool to review customer tickets and get their details. tool_id: - type: haystack_integrations.tools.mcp.MCPToolset data: server_info: type: haystack_integrations.tools.mcp.mcp_tool.StreamableHttpServerInfo url: https://api.githubcopilot.com/mcp/ timeout: 900 token: type: env_var strict: true env_vars: - GITHUB_MCP_TOKEN_83168973 tool_names: - add_comment_to_pending_review - add_issue_comment - add_reply_to_pull_request_comment - assign_copilot_to_issue - create_branch - create_or_update_file - create_pull_request - create_pull_request_with_copilot - create_repository - delete_file - fork_repository - get_commit - get_copilot_job_status - get_file_contents - get_label - get_latest_release - get_me - get_release_by_tag - get_tag - get_team_members - get_teams - issue_read - issue_write - list_branches - list_commits - list_issue_types - list_issues - list_pull_requests - list_releases - list_tags - merge_pull_request - pull_request_read - pull_request_review_write - push_files - request_copilot_review - run_secret_scanning - search_code - search_issues - search_pull_requests - search_repositories - search_users - sub_issue_write - update_pull_request - update_pull_request_branch eager_connect: false _meta: name: Github description: tool_id: system_prompt: >- {% message role="system" %} You are a helpful assistant. Answer user's questions in a polite and professional manner. Use customer_support_triage_agent to get the details of the customer and the problem they have. Use Github to browse the repository for similar issues and their reso {% endmessage %} user_prompt: "Question: {{ query }}" required_variables: - query exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: connections: [] max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages query: - Agent.query outputs: messages: Agent.messages ``` ### Pipeline as a Tool This is an agent that uses `internal_search` (a RAG pipeline) as a tool: ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.2 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: internal_search description: Use internal_search to search the company database and find information about the company and its processes. input_mapping: query: - retriever.query - ranker.query - LLM.question filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources output_mapping: attachments_joiner.documents: documents LLM.messages: messages pipeline: components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: >- {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: LLM.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: documents: source: documents messages: source: messages outputs_to_state: documents: source: documents parameters: $defs: ByteStream: properties: data: description: The binary data stored in Bytestream. format: binary type: string meta: additionalProperties: true default: {} description: Additional metadata to be stored with the ByteStream. type: object mime_type: anyOf: - type: string - type: 'null' default: description: The mime type of the binary data. required: - data type: object description: "A component that combines: 'retriever': Runs the wrapped pipeline with the provided inputs., 'ranker': Returns a list of documents ranked by their similarity to the given query., 'LLM': Process messages and generate a response from the language model., 'multi_file_converter': Runs the wrapped pipeline with the provided inputs." properties: query: description: "Provided to the 'ranker' component as: 'The input query to compare the documents to.', and Provided to the 'answer_builder' component as: 'The query used in the prompts for the Generator.'." type: string filters: description: Input 'filters' for the component. anyOf: - additionalProperties: true type: object - type: "null" files: description: Input 'files' for the component. items: anyOf: - type: string - format: path type: string - $ref: '#/$defs/ByteStream' type: array required: - query - files type: object _meta: name: internal_search description: Use internal_search to search the company database and find information about the company and its processes. tool_id: system_prompt: "You are a deep research assistant. You create comprehensive research reports to answer the user's questions. You use the 'internal_search' tool to answer any questions about the company and its processes. You perform multiple searches until you have the information you need to answer the question. Make sure you research different aspects of the question. Use markdown to format your response. When answering, cite your sources using markdown links. It is important that you cite accurately." exit_conditions: state_schema: documents: type: list[haystack.dataclasses.document.Document] _meta: used_by: internal_search: output max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: connections: [] max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages outputs: documents: Agent.documents ``` ### Adding Sources to Agent Results To show the sources or documents the Agent used to generate its answer, configure the Agent to output those documents. To do this, open the configuration of the tool that outputs the documents and choose to output them to **State**. The Agent then outputs the documents through its output connection called `documents`. You can connect `Agent`'s `documents` output to the `Output` component's `documents` input. ```yaml # haystack-pipeline components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: init_parameters: model: gpt-5.2 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: internal_search description: Use internal_search to search the company database and find information about the company and its processes. input_mapping: query: - retriever.query - ranker.query - LLM.question filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources output_mapping: attachments_joiner.documents: documents LLM.messages: messages pipeline: components: retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: >- {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: LLM.documents max_runs_per_component: 100 metadata: {} is_pipeline_async: false inputs_from_state: {} outputs_to_string: messages: source: messages outputs_to_state: documents: source: documents parameters: $defs: ByteStream: properties: data: description: The binary data stored in Bytestream. format: binary type: string meta: additionalProperties: true default: {} description: Additional metadata to be stored with the ByteStream. type: object mime_type: anyOf: - type: string - type: 'null' default: description: The mime type of the binary data. required: - data type: object description: "A component that combines: 'retriever': Runs the wrapped pipeline with the provided inputs., 'ranker': Returns a list of documents ranked by their similarity to the given query., 'LLM': Process messages and generate a response from the language model., 'multi_file_converter': Runs the wrapped pipeline with the provided inputs." properties: query: description: "Provided to the 'ranker' component as: 'The input query to compare the documents to.', and Provided to the 'answer_builder' component as: 'The query used in the prompts for the Generator.'." type: string filters: description: Input 'filters' for the component. anyOf: - additionalProperties: true type: object - type: "null" files: description: Input 'files' for the component. items: anyOf: - type: string - format: path type: string - $ref: '#/$defs/ByteStream' type: array required: - query - files type: object _meta: name: internal_search description: Use internal_search to search the company database and find information about the company and its processes. tool_id: system_prompt: >- {% message role="system" %} You are a deep research assistant. You create comprehensive research reports to answer the user's questions. You use the 'internal_search' tool to answer any questions about the company and its processes. You perform multiple searches until you have the information you need to answer the question. Make sure you research different aspects of the question. Use markdown to format your response. When answering, cite your sources using markdown links. It is important that you cite accurately. {% endmessage %} exit_conditions: state_schema: documents: type: list[haystack.dataclasses.document.Document] _meta: used_by: internal_search: output max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: connections: [] max_runs_per_component: 100 metadata: {} inputs: messages: - Agent.messages outputs: documents: Agent.documents messages: Agent.messages ``` ## Parameters ### Inputs | Parameter | Type |Default| Description | |------------------|----------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |Optional[List[ChatMessage]] |None |List of Haystack `ChatMessage` objects to process. Optional if the Agent has a `user_prompt` or `system_prompt` configured. If a list of dictionaries is provided, each dictionary is converted into a `ChatMessage` object. | |streaming_callback|Optional[StreamingCallbackT]|None |A callback function to invoke when a response is streamed from the LLM. You can configure the same callback function for emitting tool results when the agent calls a tool.| |system_prompt |Optional[str] |None |System prompt for this specific run. Supports Jinja2 message template syntax for dynamic content. If provided, it overrides the default system prompt configured during initialization. This allows you to dynamically adjust the Agent's behavior for different queries.| |tools |Optional[Union[List[Tool], Toolset, List[str]]]|None|Optional list of Tool objects, a Toolset, or list of tool names to use for this run. When passing tool names, tools are selected from the Agent's originally configured tools. This allows you to dynamically select which tools the Agent uses at query time.| |kwargs |Any | |Additional inputs forwarded to the Agent's state. The keys must match the schema defined in the Agent's `state_schema`. | ### Outputs |Output|Type|Description| |------|----|-----------| |messages|List[ChatMessage]|Complete conversation history including all messages from the Agent run: user messages, LLM responses, tool calls, and tool results.| |last_message|ChatMessage|The final message from the Agent run, typically containing the LLM's final response. This is useful when you only need the final result.| |Additional state outputs|Varies|Any fields defined in `state_schema` are also returned as outputs (for example, `documents`, `repository`).| Unlike a `ChatGenerator,` which returns only the final message, the Agent returns all messages generated during the process. This includes the messages provided as input.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type |Default| Description | |--------------------------------|------------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |chat_generator |ChatGenerator | |The chat generator that the agent will use. You configure the generator by passing its init parameters and type to the Agent. Check the Usage Example section for details. The chat generator must support tools. Each chat generator exposes a `SUPPORTED_MODELS` class variable that lists the models it supports. | |tools |Optional[Union[List[Tool], Toolset]]|None |External tools or toolsets the Agent can use. You can provide individual Tool objects as a list, or organize related tools into a Toolset. | |system_prompt |Optional[str] |None |System prompt to guide the Agent's behavior. Supports Jinja2 message template syntax with `{% message role='system' %}...{% endmessage %}` for dynamic content injection at runtime. When using Jinja2 syntax, you can pass variables through `required_variables`. This can be overridden at runtime by passing a `system_prompt` parameter to the run method.| |user_prompt |Optional[str] |None |A reusable Jinja2-templated user prompt. If provided, this is rendered with the given variables and appended to the messages provided at runtime. This lets you invoke the Agent with dynamic inputs without manually constructing `ChatMessage` objects. Can be overridden at runtime.| |required_variables |Optional[Union[List[str], Literal["*"]]]|None|List of variables that must be provided as input to the `user_prompt` or `system_prompt`. If a required variable is not provided, an exception is raised. Set to `"*"` to require all variables found in the prompts.| |exit_conditions |Optional[List[str]] |["text"]|Defines when the agent stops processing messages. Pass `"text"` to stop the Agent when it generates a message without tool calls. Pass the name of a tool to stop the Agent after it successfully runs this tool. Multiple exit conditions can be specified, and the Agent stops when any one is met.| |state_schema |Optional[Dict[str, Any]] |None |Optional schema for managing the runtime state used by tools. It defines extra information—such as documents or context—that tools can read from or write to during execution. You can use this schema to pass parameters that tools can both produce and consume during a call. This means that when a pipeline runs, tools can read from the Agent's state (for example, the current set of retrieved documents) and write into or update this state as they run. | |max_agent_steps |int |100 |Maximum number of steps (LLM calls) the Agent runs before stopping. Defaults to 100. If the Agent reaches this limit, it stops execution and returns all messages and state accumulated up to that point. A warning is logged when this limit is reached. Increase this value for complex tasks that require many tool calls. | |streaming_callback |Optional[StreamingCallbackT] |None |Function invoked for streaming responses. To enable streaming, set `streaming_callback` to `deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback`. To learn more about streaming, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | |raise_on_tool_invocation_failure|bool |False |Whether to raise an error when a tool call fails. If set to `False`, the exception is turned into a chat message and passed to the LLM. | |tool_invoker_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments to pass when invoking a tool. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |------------------|----------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |Optional[List[ChatMessage]] |None |List of Haystack ChatMessage objects to process. Optional if the Agent has a `user_prompt` or `system_prompt` configured. If a list of dictionaries is provided, each dictionary is converted to a ChatMessage object. | |streaming_callback|Optional[StreamingCallbackT]|None |A function to handle streamed responses. You can configure the same callback function to emit tool results when a tool is called.| |system_prompt |Optional[str] |None |System prompt for this specific run. Supports Jinja2 message template syntax for dynamic content. If provided, it overrides the default system prompt configured during initialization. This allows you to dynamically adjust the Agent's behavior for different queries.| |user_prompt |Optional[str] |None |User prompt for this specific run. If provided, it overrides the default `user_prompt` configured during initialization. The rendered prompt is appended to the provided messages.| |generation_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments for the LLM. These parameters override the parameters passed during component initialization, allowing fine-grained control over chat generation at runtime.| |tools |Optional[Union[List[Tool], Toolset, List[str]]]|None|Optional list of Tool objects, a Toolset, or list of tool names to use for this run. When passing tool names, tools are selected from the Agent's originally configured tools. This allows you to dynamically select which tools the Agent uses at query time.| |break_point |Optional[AgentBreakpoint] |None |An AgentBreakpoint, can be a Breakpoint for the "chat_generator" or a ToolBreakpoint for "tool_invoker". Used for debugging and monitoring agent execution.| |snapshot |Optional[AgentSnapshot] |None |A dictionary containing a snapshot of a previously saved agent execution. The snapshot contains the relevant information to restart the Agent execution from where it left off.| |kwargs |Any | |Additional parameters to pass to the Agent's `state_schema`. The keys must match the schema defined in the Agent's `state_schema`. | ## Related Information - [AI Agents](/docs/concepts/ai-agents/ai-agent.mdx) - [Building AI Agents](/docs/how-to-guides/building-agents/building-ai-agents.mdx) --- ## DALLEImageGenerator Generate images from text prompts using OpenAI's DALL-E model. The component accepts a text prompt, sends it to the DALL-E API, and returns the generated images along with any revised prompt OpenAI used. ## Key Features - Supports both DALL-E 2 and DALL-E 3 models. - Configurable image quality (standard or HD) and size. - Returns images as URLs or base64-encoded JSON strings. - Returns the revised prompt OpenAI used for image generation. - Compatible with `PromptBuilder` for dynamic prompt construction. ## Configuration :::tip Authentication To use this component, connect with OpenAI first. For detailed instructions, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). ::: 1. Drag the `DALLEImageGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the model: `dall-e-2` or `dall-e-3`. 2. Choose the image quality: `standard` or `hd`. 3. Set the image size. For `dall-e-2`, choose from 256x256, 512x512, or 1024x1024. For `dall-e-3`, choose from 1024x1024, 1792x1024, or 1024x1792. 4. Set the response format: `url` to receive image URLs, or `b64_json` for base64-encoded images. 4. Go to the **Advanced** tab to configure the OpenAI API key, timeout, maximum retries, API base URL, organization ID, and HTTP client settings. ## Connections `DALLEImageGenerator` accepts a `prompt` string as input. It outputs a list of images (`images`) and the revised prompt (`revised_prompt`) OpenAI used for generation. Typically, you connect a `PromptBuilder` to the `DALLEImageGenerator`'s `prompt` input to build dynamic prompts. The `images` and `revised_prompt` outputs connect to an `OutputAdapter` or `AnswerBuilder` for further processing. ## Source Code To check this component's source code, open [`openai_dalle.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/openai_dalle.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml dalle_image_generator: type: haystack.components.generators.openai_dalle.DALLEImageGenerator init_parameters: model: dall-e-3 quality: standard size: 1024x1024 response_format: url timeout: 60 ``` ### Image Generation Pipeline This pipeline uses `DALLEImageGenerator` to generate images based on a query: ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: '{{query}}' dalle_image_generator: type: haystack.components.generators.openai_dalle.DALLEImageGenerator init_parameters: model: dall-e-3 quality: standard size: 1024x1024 response_format: url timeout: 60 answer_formatter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: |- {% set ns = namespace(doc_string='') %} {% set ns.doc_string = ns.doc_string + '## Query:\n' + query + '\n\n' %} {% set ns.doc_string = ns.doc_string + '## OpenAIs Revised Prompt:\n' + revised_prompt + '\n\n' %} {% set ns.doc_string = ns.doc_string + '![](' + images[0] + ')' + '\n\n' %} {% set answer = [ns.doc_string] %} {{ answer }} output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: {} connections: - sender: prompt_builder.prompt receiver: dalle_image_generator.prompt - sender: dalle_image_generator.revised_prompt receiver: answer_formatter.revised_prompt - sender: dalle_image_generator.images receiver: answer_formatter.images - sender: answer_formatter.output receiver: answer_builder.replies - sender: prompt_builder.prompt receiver: answer_builder.prompt max_runs_per_component: 100 metadata: {} inputs: query: - prompt_builder.query - answer_formatter.query - answer_builder.query outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type |Default| Description | |---------------|------------------------------------------------------------------------------|-------|--------------------------------------------------------------------------| |prompt |str | |The prompt to generate the image. | |size |Optional[Literal['256x256', '512x512', '1024x1024', '1792x1024', '1024x1792']]|None |If provided, overrides the size provided during initialization. | |quality |Optional[Literal['standard', 'hd']] |None |If provided, overrides the quality provided during initialization. | |response_format|Optional[Optional[Literal['url', 'b64_json']]] |None |If provided, overrides the response format provided during initialization.| ### Outputs | Parameter | Type | Description | |--------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |images |List[str]|A list of generated images. Depending on the `response_format` parameter, the images are URLs or base64-encoded JSON strings.| |revised_prompt|str |The prompt OpenAI used to generate the image. OpenAI may revise the original prompt before generating the image.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|--------------------------------------------------------------------|-------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |str |dall-e-3 |The model to use for image generation. Can be "dall-e-2" or "dall-e-3". | |quality |Literal['standard', 'hd'] |standard |The quality of the generated image. Can be "standard" or "hd". | |size |Literal['256x256', '512x512', '1024x1024', '1792x1024', '1024x1792']|1024x1024 |The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. | |response_format |Literal['url', 'b64_json'] |url |The format of the response. Can be "url" or "b64_json". | |api_key |Secret |Secret.from_env_var('OPENAI_API_KEY')|The OpenAI API key to connect to OpenAI. | |api_base_url |Optional[str] |None |An optional base URL. | |organization |Optional[str] |None |The Organization ID, defaults to `None`. | |timeout |Optional[float] |None |Timeout for OpenAI Client calls. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30. | |max_retries |Optional[int] |None |Maximum retries to establish contact with OpenAI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]] |None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|------------------------------------------------------------------------------|-------|--------------------------------------------------------------------------| |prompt |str | |The prompt to generate the image. | |size |Optional[Literal['256x256', '512x512', '1024x1024', '1792x1024', '1024x1792']]|None |If provided, overrides the size provided during initialization. | |quality |Optional[Literal['standard', 'hd']] |None |If provided, overrides the quality provided during initialization. | |response_format|Optional[Optional[Literal['url', 'b64_json']]] |None |If provided, overrides the response format provided during initialization.| ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ExtractiveReader Locate and extract answers to a query directly from documents using a transformer-based question answering model. Unlike generative models, `ExtractiveReader` returns exact spans of text from the source documents as answers. ## Key Features - Assigns independent scores to every possible answer span, making comparisons across documents consistent. - Returns a configurable number of top answers ranked by score. - Supports a score threshold to filter out low-confidence answers. - Optionally returns a "no answer" result when no confident answer is found. - Removes duplicate answers based on a configurable overlap threshold. - Works with any HuggingFace question answering model. ## Configuration 1. Drag the `ExtractiveReader` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, enter the model to use. This can be a HuggingFace Hub model ID (for example, `deepset/roberta-base-squad2-distilled`) or a path to a local folder containing the model files. 4. Optionally, go to the **Advanced** tab to configure more settings, like `top_k`, model kwargs, `score_threshold` to filter out answers below a minimum confidence score, and more. ## Connections `ExtractiveReader` accepts a `query` string and a list of `Document` objects as inputs. It outputs a list of `ExtractedAnswer` objects ranked by score. Typically, you connect a retriever (such as `OpenSearchBM25Retriever`) or a `Ranker` to the `ExtractiveReader`'s `documents` input, and pass the user query to its `query` input. The `answers` output then connects to `Output`'s `answers` input to get the final response. ## Source Code To check this component's source code, open [`extractive.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/readers/extractive.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml reader: type: haystack.components.readers.extractive.ExtractiveReader init_parameters: answers_per_seq: 20 calibration_factor: 1.0 max_seq_length: 384 model: "deepset/deberta-v3-large-squad2" model_kwargs: torch_dtype: "torch.float16" no_answer: false top_k: 10 ``` ### Using ExtractiveReader in a Pipeline `ExtractiveReader` is typically used in a pipeline to extract answers from a list of documents. Here's an example: ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 10 reader: type: haystack.components.readers.extractive.ExtractiveReader init_parameters: answers_per_seq: 20 calibration_factor: 1.0 max_seq_length: 384 model: "deepset/deberta-v3-large-squad2" model_kwargs: torch_dtype: "torch.float16" no_answer: false top_k: 10 attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: attachments_joiner.documents - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: reader.documents inputs: query: - retriever.query - ranker.query - reader.query filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources outputs: documents: attachments_joiner.documents answers: reader.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs 1. Drag the `ExtractiveReader` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Select the model: enter a Hugging Face model identifier or a local path. The default is `deepset/roberta-base-squad2-distilled`. 4. Go to the **Advanced** tab to configure the device, API token, top_k, score threshold, maximum sequence length, stride, batch size, answers per sequence, no-answer scoring, calibration factor, overlap threshold, and model keyword arguments. ## Connections ### Outputs |Parameter| Type | Description | |---------|---------------------|-----------------------------------------------| |answers |List[ExtractedAnswer]|List of answers sorted by (desc.) answer score.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|-------------------------|---------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Union[Path, str] |deepset/roberta-base-squad2-distilled |A Hugging Face transformers question answering model. Can either be a path to a folder containing the model files or an identifier for the Hugging Face hub. | |device |Optional[ComponentDevice]|None |The device on which the model is loaded. If `None`, the default device is automatically selected. | |token |Optional[Secret] |Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False)|The API token used to download private models from Hugging Face. | |top_k |int |20 |Number of answers to return per query. It is required even if score_threshold is set. An additional answer with no text is returned if no_answer is set to True (default). | |score_threshold |Optional[float] |None |Returns only answers with the probability score above this threshold. | |max_seq_length |int |384 |Maximum number of tokens. If a sequence exceeds it, the sequence is split. | |stride |int |128 |Number of tokens that overlap when sequence is split because it exceeds max_seq_length. | |max_batch_size |Optional[int] |None |Maximum number of samples that are fed through the model at the same time. | |answers_per_seq |Optional[int] |None |Number of answer candidates to consider per sequence. This is relevant when a Document was split into multiple sequences because of max_seq_length. | |no_answer |bool |True |Whether to return an additional `no answer` with an empty text and a score representing the probability that the other top_k answers are incorrect. | |calibration_factor|float |0.1 |Factor used for calibrating probabilities. | |overlap_threshold |Optional[float] |0.01 |If set this will remove duplicate answers if they have an overlap larger than the supplied threshold. For example, for the answers "in the river in Maine" and "the river" we would remove one of these answers since the second answer has a 100% (1.0) overlap with the first answer. However, for the answers "the river in" and "in Maine" there is only a max overlap percentage of 25% so both of these answers could be kept if this variable is set to 0.24 or lower. If None is provided then all answers are kept.| |model_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments passed to `AutoModelForQuestionAnswering.from_pretrained` when loading the model specified in `model`. For details on what kwargs you can pass, see the model's documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |-----------------|---------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query |str | |Query string. | |documents |List[Document] | |List of Documents in which you want to search for an answer to the query. | |top_k |Optional[int] |None |The maximum number of answers to return. An additional answer is returned if no_answer is set to True (default). | |score_threshold |Optional[float]|None |Returns only answers with the score above this threshold. | |max_seq_length |Optional[int] |None |Maximum number of tokens. If a sequence exceeds it, the sequence is split. | |stride |Optional[int] |None |Number of tokens that overlap when sequence is split because it exceeds max_seq_length. | |max_batch_size |Optional[int] |None |Maximum number of samples that are fed through the model at the same time. | |answers_per_seq |Optional[int] |None |Number of answer candidates to consider per sequence. This is relevant when a Document was split into multiple sequences because of max_seq_length. | |no_answer |Optional[bool] |None |Whether to return no answer scores. | |overlap_threshold|Optional[float]|None |If set this will remove duplicate answers if they have an overlap larger than the supplied threshold. For example, for the answers "in the river in Maine" and "the river" we would remove one of these answers since the second answer has a 100% (1.0) overlap with the first answer. However, for the answers "the river in" and "in Maine" there is only a max overlap percentage of 25% so both of these answers could be kept if this variable is set to 0.24 or lower. If None is provided then all answers are kept.| --- ## LLM Generate text using a large language model (LLM). This component provides a single interface for single-turn text generation without using tools. :::tip Simplify Your Pipelines `LLM` replaces `ChatPromptBuilder` and `ChatGenerator` components. If you're using `ChatPromptBuilder` and `ChatGenerator` components, you can simplify your pipelines by using the `LLM` component instead. For details, see [Simplify Pipelines](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ::: Unlike the `Agent` component, `LLM` only generates text, it doesn't call tools. You send messages to the component, it forwards them to the configured LLM provider, and it returns a single response. `LLM` is model-agnostic, which means you can use it with any LLM provider, such as OpenAI, Azure, or any other compatible one. ## Key Features - Flexible prompting: Supports system prompts, user prompts, and Jinja2 template variables in prompts. - Model agnostic: Works with any LLM. - Streaming support: Streams responses token by token. - Replaces ChatPromptBuilder and ChatGenerator components. ## When to Use LLM versus Agent If all you need is straightforward text generation without tools, choose `LLM`. For tool calling, multi-step reasoning, or exit conditions, use the `Agent` component instead. ## Configuration :::note User Prompt You must configure a user prompt with at least one variable. If you don't configure a user prompt, the `LLM` will not produce any output. ::: 1. Drag the `LLM` component from the Component Library onto the canvas. 2. Click **Model** on the component card to open the configuration panel. 3. On the **General** tab: 1. Choose the model from the list. Make sure is connected to the model provider. For help, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). 2. Optionally, enter a system prompt to configure the model's behavior. System prompt is in a string format. 3. Enter a user prompt with at least one variable. User prompt supports Jinja2 syntax, so you can use variables and functions in the prompt. For examples, see the *Examples* section below. For instructions on writing prompts, see [Writing Prompts in ](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). :::tip Jinja in the `LLM` component When you add or edit a prompt for the `LLM` component, you write regular text. To insert a variable, type **`@`** and a list of available variables appears so you can pick one. To insert a function, type **`/`** and you see all functions you can add to the template. To see the raw Jinja2 syntax, enable the **Jinja** toggle. It's disabled by default. ::: 4. To configure the model's behavior, open the **Advanced** tab and set model parameters. The parameters are specific to the model you chose. ## Connections The `LLM`'s input connections depend on the user prompt configured. By default, it accepts a list of `ChatMessage` objects through its `messages` input. It outputs a single `ChatMessage` object through its `last_message` output and a list of `ChatMessage` objects through its `messages` output. The `messages` output is a concatenated system prompt, messages provided as input, user prompt, and the LLM's answer appended at the end. :::tip Last Message vs Messages If `LLM` is the component that produces the final answer, the `last_message` output is the LLM's answer. That's the output you want to use as the final output of the pipeline. You can connect `last_message` to the `Output` component's `messages` input. ::: You can connect it directly to the `query` output of the `Input` component or to any component that produces `ChatMessage` or `string` output. You can send its `messages` output to `Input`'s `messages` input or to another `LLM`. ## Source Code To check this component's source code, open [`llm.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/llm.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration This is the basic LLM configuration, with a model, system prompt, and user prompt. The user prompt includes the variable `document` that will be dynamically inserted into the prompt when the LLM runs. ```yaml LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: |- {% message role="system" %} You are a helpful assistant that translates documents. {% endmessage %} user_prompt: |- {% message role="user" %} Translate the following document: {{ document }} {% endmessage %} required_variables: - document streaming_callback: ``` ### The Simplest Working Pipeline To build the simplest pipeline with the LLM component: 1. Drag the `Input` component onto the canvas. 2. Drag the `LLM` component onto the canvas and configure its user prompt with at least one variable. A basic prompt could be `Answer the question: {{ query }}`. 3. Connect `Input`'s `query` output to the `LLM`'s `query` input. 4. Connect the `LLM`'s `last_message` output to the `Output`'s `messages` input. You can now run the pipeline to test it. It uses the LLM's knowledge to answer questions. Pipeline YAML: ```yaml # haystack-pipeline components: LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: '' user_prompt: |- {% message role="user" %} Answer the user query: {{ query }} {% endmessage %} required_variables: '*' streaming_callback: connections: [] max_runs_per_component: 100 metadata: {} inputs: query: - LLM.query outputs: messages: LLM.last_message ``` ### Summarization Pipeline Here's a pipeline that uses `LLM` to summarize retrieved documents: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: standard-index embedding_dim: 768 return_embedding: false create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false max_chunk_bytes: 104857600 method: mappings: settings: timeout: top_k: 10 llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-5-mini system_prompt: "You are a helpful assistant. Answer the question based on the provided documents. If the documents don't contain the answer, say so." user_prompt: |- {% message role="user"%} Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} {% endmessage %} required_variables: - documents - question connections: - sender: bm25_retriever.documents receiver: llm.documents max_runs_per_component: 100 inputs: query: - bm25_retriever.query question: - llm.question metadata: {} outputs: documents: bm25_retriever.documents messages: llm.last_message ``` ## Parameters ### Inputs | Parameter | Type | Description | | :------------------- | :--------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | Optional[List[ChatMessage]] | A list of `ChatMessage` objects to process. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for the LLM. These override the parameters passed during initialization. | | `system_prompt` | Optional[str] | The system prompt for the LLM. If provided, it overrides the system prompt set during initialization. | | `user_prompt` | Optional[str] | The user prompt for the LLM. If provided, it overrides the default user prompt and is appended to the messages provided at runtime. | | `**kwargs` | Any | Additional keyword arguments used to fill template variables in the `user_prompt`. The keys must match the template variable names. | ### Outputs | Parameter | Type | Description | | :------------- | :--------------- | :------------------------------------------------------- | | `messages` | List[ChatMessage]| A list of all messages exchanged during the LLM's run. | | `last_message` | ChatMessage | The last message exchanged during the LLM's run. | ### Init parameters You configure these parameters in Builder: | Parameter | Type | Default | Description | | :------------------- | :--------------------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `chat_generator` | ChatGenerator | | The chat generator the LLM uses. This can be any Haystack chat generator, such as `OpenAIChatGenerator` or `AzureOpenAIChatGenerator`. Each chat generator exposes a `SUPPORTED_MODELS` class variable that lists the models it supports. | | `system_prompt` | Optional[str] | None | A system prompt that defines how the model should behave. | | `user_prompt` | Optional[str] | None | A user prompt appended to the messages at runtime. Supports Jinja2 template variables that become additional inputs for the `run()` method. | | `required_variables` | Optional[List[str] or "*"] | None | Variables that must be provided as input to the `user_prompt`. If any are missing, an exception is raised. Set to `"*"` to require all variables found in the prompt. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that runs when a new token is received from the stream. | ### Run method parameters You can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :------------------- | :--------------------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | Optional[List[ChatMessage]] | None | A list of ChatMessage objects to process. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the underlying chat generator. These override the parameters set during initialization. | | `system_prompt` | Optional[str] | None | The system prompt for the LLM. If provided, it overrides the system prompt set during initialization. | | `user_prompt` | Optional[str] | None | The user prompt for the LLM. If provided, it overrides the default user prompt and is appended to the messages at runtime. | | `**kwargs` | Any | | Additional keyword arguments used to fill template variables in the `user_prompt`. The keys must match the template variable names. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) - [Writing Prompts](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AI Overview # AI Components Components in the AI group are powered by large language models (LLMs). Use them when you want your pipeline to understand and generate text, reason over context, follow instructions, or make decisions based on natural language input. This group includes components such as LLMs (for text generation), agents (to plan and execute multi-step tasks and call tools), and image generators (to create images from prompts). These components typically sit at the “thinking” layer of a pipeline, turning retrieved context and user input into structured actions or high-quality outputs. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## Common Component Combinations(Pipeline-components) Let's look at examples of components that often go together to understand how they work. ## PromptBuilder and Generator Generators are components designed to interact with large language models (LLMs). Any LLM app requires a Generator component specific to the model provider used. Generator needs a prompt as input, which is created using `PromptBuilder`. With `PromptBuilder`, you can define your prompt as a Jinja2 template. `PromptBuilder` processes the template, fills in the variables, and sends it to the Generator. To connect these components, link the `prompt` output of `PromptBuilder` to the `prompt` input of the `Generator`, as shown below: Example YAML configuration: ```yaml components: qa_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: qa_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0.0 seed: 0 connections: - sender: qa_prompt_builder.prompt receiver: qa_llm.prompt ``` ## ChatPromptBuilder and ChatGenerator ChatGenerators are a type of Generators designed to work with chat LLMs in conversational scenarios. They receive the rendered prompt from a `ChatPromptBuilder`. The prompt for ChatGenerators is a list of `ChatMessage` objects, which means it follows a strict format: ```yaml ChatMessage format - _content: # this is the beginning of the first ChatMessage - content_type: content # this is the message content, it can be text, tool call or a tool call result. You can add variables to the content, just like in PromptBuilder. _role: role # this specifies who sends this content, available roles are: system, tool, user, assistant ``` This is an example of a prompt with two `ChatMessage`, one for the `system` and one for the `user` role. The message for the system contains instructions for the LLM, while the message for the users contains user's query. It's also used to pass the retrieved documents to the LLM: ```yaml Example template for ChatPromptBuilder - _content: - text: | You are a helpful assistant answering the user's questions based on the provided documents. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Provided documents: {% for document in documents %} Document [{{ loop.index }}] : {{ document.content }} {% endfor %} Question: {{ query }} _role: user ``` You pass the prompt in the `template` parameter of a `ChatPromptBuilder` and then connect the `prompt` output to the `messages` input of a ChatGenerator: ## Generator and DeepsetAnswerBuilder The Generator’s output is `replies`, a list of strings containing all the answers the LLM generates. However, pipelines require outputs in the form of `Answer` objects or its subclasses, such as `GeneratedAnswer`. Since the pipeline’s output is the same as the output of its last component, you need a component that converts `replies` into the `GeneratedAnswer` format. This is why Generators are always paired with a `DeepsetAnswerBuilder`. `DeepsetAnswerBuilder` processes the Generator’s replies and transforms them into a list of `GeneratedAnswer` objects. It can also include documents in the answers, providing references to support the generated responses. This feature is particularly useful when you need answers that are backed by reliable sources. To connect these two components, you simply link Generator’s `replies` output with `DeepsetAnswerBuilder`’s `replies` input. Additionally, `DeepsetAnswerBuilder` requires the query as an input to include it in the `GeneratedAnswer`. Ensure the query is properly connected to the `DeepsetAnswerBuilder` through the `Input` component to complete the configuration. `DeepsetAnswerBuilder` also accepts the prompt as input. If it receives the prompt, it adds it to the `GeneratedAnswer`'s metadata. This is useful if you need a prompt as part of the API response from . Here’s how to connect the components: :::tip `DeepsetAnswerBuilder` is available in the _Augmenters_ group in the components library. ::: ## ChatGenerators and AnswerBuilders ChatGenerators can't connect directly to `DeepsetAnswerBuilder` as their input and output types don't match. You can use `OutputAdapter` in between to convert the ChatGenerator's output (list of `ChatMessage` objects) into a list of strings that `DeepsetAnswerBuilder` accepts: ```yaml OutputAdapter's configuration OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: typing.List[str] custom_filters: unsafe: false ``` This how you build the connections in Pipeline Builder: Another option is to simply use `AnswerBuilder` after a ChatGenerator. Their inputs and outputs are compatible. :::info AnswerBuilder and DeepsetAnswerBuilder The main difference between `AnswerBuilder` and `DeepsetAnswerBuilder` is that the latter is better at handling complicated references and can extract content from XML tags. ::: ## Embedders Embedders are a group of components that turn text or documents into vectors (embeddings) using models trained to do that. Embedders are specific to the model provider, with at least two embedders available for each: - Document Embedder - Text Embedder Document Embedders are used in indexing pipelines to embed documents before they’re written into the document store. In most cases, this means a `DocumentEmbedder` is connected to the `DocumentWriter`: The connection is simple - you link `DocumentEmbedder`’s `documents` output with `DocumentWriter`’s `documents` input. Text Embedders are used in query pipelines to embed the query text and pass it on to the next component, typically a Retriever. The `Input` component’s `text` output is connected to the `TextEmbedder`’s `text` input. The `TextEmbedder` then generates embeddings, and its `embedding` output is linked to the `query_embedding` input of the Retriever. Keep in mind that the `DocumentEmbedder` in your indexing pipeline and the `TextEmbedder` in your query pipeline must use the same model. This ensures the embeddings are compatible for accurate retrieval. --- ## Code Add your own Python code to a pipeline quickly and easily. The `Code` component validates your code instantly as you type it. ## Key Features - Write and run custom Python logic directly in Pipeline Builder without creating a separate custom component. - Code is validated as you type, with errors shown inline. - Supports saving and reusing components across multiple pipelines. - Inputs and outputs are defined dynamically through the `run()` method, so the component connects to any other component with matching types. - Includes an AI assistant to help generate code. - Works with all standard dependencies available in . - When your class defines `__init__` parameters, an **Advanced** tab appears in the configuration panel so you can set those values from the UI. ## Configuration 1. Drag the `Code` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Enter or paste your Python code in the `code` field. The code must define exactly one class decorated with `@component` and expose a `run()` method. The component validates your code as you type. If there are errors, a red error message appears in the `code` field. 4. If your class defines `__init__` parameters, click the **Advanced** tab in the configuration panel to set their values. Each parameter appears as an inline control — a text field for strings, a number field for numbers, a toggle for booleans, and a dropdown for enum types. For complex types such as objects or dicts, an expandable editor appears. :::tip AI assistant You can use the AI assistant to generate code for your `Code` component. To do this, click the **AI Assistant** button on the component card and write your request in the prompt. ::: ## Connections You define the `Code` component's inputs and outputs in its `run()` method. The component connects to any other component whose inputs and outputs match the types you declare. Make sure the types in your `run()` method signature match the types of the components you want to connect to. ### Available Dependencies Your `Code` component has access to standard dependencies available in . Expand this section to check available dependencies:
Available Dependencies
## Usage Examples ### Basic Configuration ```yaml Code: type: deepset_cloud_custom_nodes.code.code_component.Code init_parameters: code: | from haystack import component @component class Code: @component.output_types(result=str) def run(self, text: str) -> dict: return {"result": text.upper()} ``` ### Masking Sensitive Information This is a query pipeline that masks sensitive information, like emails or phone numbers, before sending the data to an LLM. `pii_redactor` is a `Code` component with custom Python code that masks the sensitive information. ```yaml # haystack-pipeline components: pii_redactor: type: deepset_cloud_custom_nodes.code.code_component.Code init_parameters: code: | from haystack import component @component class Code: """Masks personally identifiable information before LLM processing.""" @component.output_types(redacted_text=str, pii_found=bool) def run(self, text: str) -> dict: redacted = text pii_found = False # Email addresses email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' if re.search(email_pattern, redacted): pii_found = True redacted = re.sub(email_pattern, '[EMAIL]', redacted) # Phone numbers (various formats) phone_pattern = r'\b(\+?1?[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b' if re.search(phone_pattern, redacted): pii_found = True redacted = re.sub(phone_pattern, '[PHONE]', redacted) return {"redacted_text": redacted, "pii_found": pii_found} prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Help the user with their request: {{ query }} llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-4o-mini api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: pii_redactor.redacted_text receiver: prompt_builder.query - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies inputs: query: - answer_builder.query - pii_redactor.text outputs: answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` This is what the component looks like in the Builder: ## Parameters ### Inputs You define the inputs in the `run()` method of your inline component. Whatever arguments you declare become the component's inputs. Make sure their types match the output types of the components you want to connect to. ### Outputs You define the outputs using the `@component.output_types` decorator on your `run()` method. Whatever output types you declare become the component's outputs. Make sure their types match the input types of the components you want to connect to. ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |code|str| |Python source that defines exactly one class decorated with `@component`. The class must expose a `run()` method. If the class defines `__init__` parameters, they appear on the **Advanced** tab in the configuration panel.| |input_names|List[str]| |Names of the input variables for the component, corresponding to the parameters of the `run()` method.| |output_names|List[str]| |Names of the output variables for the component, corresponding to the values declared in `@component.output_types`.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |Inputs defined in your code|Dynamic|Inherited from the wrapped component|Whatever arguments your inline component declares become keyword arguments for `run()`. Set them the same way you would configure any other component parameter.| ## Troubleshooting - **"No Haystack component found" error**: Add the `@component` decorator to your class and keep only one component definition inside the `code` string. - **Type errors during `run()`**: Ensure upstream nodes send the exact data types your inline component expects. Mismatched socket names or missing keyword arguments raise `TypeError` because `Code` forwards inputs directly to the wrapped component. ## Performance Considerations - `Code` executes your snippet once during pipeline load, so heavy imports or long module-level logic slow down startup but not per-request execution. - The inline component runs synchronously with the rest of the pipeline. Complex logic in `run()` increases latency in lockstep. - Treat the `code` field like executable configuration. Store only trusted code and monitor version control changes to keep track of what runs inside your pipelines. ## Related Information - [Add a Code Component](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/create-code-component.mdx) - [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## Custom Components(Pipeline-components) Custom components are a way to execute your own Python code in your pipelines. *** ## Why Custom Components? While we offer multiple pre-built components to handle various tasks, you might need something more tailored to your needs. This is when custom components come in. With custom components, you can add your own code that: - Adjusts the functionality to your specific needs and use cases. - Integrates proprietary algorithms or business logic. - Extends the pipeline's capabilities. uses 's open source Haystack framework as the underlying technology. Custom components are based on Haystack's [components](https://docs.haystack.deepset.ai/docs/components). To learn more about Haystack, visit [the Haystack website](https://haystack.deepset.ai/). To learn about custom components in Haystack, see [Creating Custom Components](https://docs.haystack.deepset.ai/docs/custom-components). ## Custom Components vs `Code` Component You can add custom code to your pipelines by creating a custom component or using the `Code` component. Custom components are a good choice if you want to share your code with the rest of the organization and reuse it in multiple pipelines. You create custom components by forking our template and updating it as needed. You then upload your code to . The `Code` component is a good choice if you want to add code to a single pipeline and don't need to share it with the rest of the organization. It's faster and easier to add than a custom component, but it has a limited scope. This table summarizes the differences between the two approaches: | Feature | Custom Components | `Code` Component | |---------|------------------|-----------------| | Sharing | Share with the rest of the organization | Not shared, scope limited to a single pipeline | | Reusability | Easily reusable in multiple pipelines in the whole organization; the component becomes available in Your Custom Components in the Component Library | Only reusable by copying the component definition into another pipeline | | Visibility | Visible to the rest of the organization, custom components are added to Your Custom Components in the Component Library | Code only visible in the pipeline where it's added| | Code versioning | Versioning is supported. You can use a version control system, like GitHub. | No versioning beyond pipeline versioning | | Code testing | You can add testing through CI/CD. For example, you can use GitHub Actions to run tests when you push your code to GitHub. | Testing is not supported | | Updates | Updates to a custom component apply to all pipelines that use it | Updates apply only to the pipeline where the component is added| | External dependencies | Supported | Not supported beyond dependencies already available in (include many standard dependencies) | | Creation method | Forking a GitHub repository, updating the code, and uploading it to | Adding code to the `Code` component available in Builder | For detailed instructions, see [Add Custom Code](/docs/how-to-guides/designing-your-pipeline/work-with-custom-components/add-custom-code.mdx). ## Adding Custom Components ### Custom Components Template ### Workflow Here's the whole workflow, step-by-step: 1. Fork the [GitHub](https://github.com/deepset-ai/dc-custom-component-template) template we provide. 2. Use the template to create your custom components. 3. When your components are ready, import them to . You can do this by creating a release of your repository or zipping the template package and uploading it to using the API or the commands. The package is validated on upload to check if its structure complies with the template. 4. Check the upload status: 1. If you uploaded through a repository release, check the Actions tab. If all the checks have passed, your component is uploaded. 2. If you uploaded using API or commands, use the [Get Custom Component](/docs/api/main/get-custom-component-api-v-2-custom-components-custom-component-id-get.api.mdx) endpoint. If the component is uploaded successfully, you can use it in your pipelines. 3. Or simply edit a pipeline where you want to use your custom component and check if your component is already in the component library. 5. Use the component in your pipelines just like any other component. Components support dependencies and have access to the internet. Currently, you can't delete custom components. To update custom components, upload a new version. ### Template Structure We offer a template for creating custom components you can access at [GitHub](https://github.com/deepset-ai/dc-custom-component-template). There are two files in the repo that you'll need to modify: - `./dc-custom-component-template/src/dc_custom_component/example_components//.py`: This is where your component code is stored. The base path `./dc-custom-component-template/src/dc_custom_component/` must remain unchanged, but you can create additional subfolders to organize your custom components within the `dc_custom_component` folder. You can create a separate folder for each component, with its own `.py` file, or group multiple components in a single folder and manage them through one `.py` file. Whatever works best for you. The folder name appears as the group's name in the components library in Pipeline Builder, where you can find your custom component. For example, if you place your custom component under `./dc-custom-component-template/src/dc_custom_component/components/rankers/custom_ranker.py`, it will show up in Pipeline Builder in the Rankers group. - `./dc-custom-component-template/src/dc_custom_component/__about__.py`: This is the component version. Make sure to update it here every time you upload a new version. The version is set for all components in the package. - `./dc-custom-component-template/pyproject.toml`: If your component has any dependencies, you can add them in this file in the `dependencies` section. ### Versioning Here's how pipelines use your custom component versions: - New pipelines can only use the latest version of your components. - Running pipelines use the component version that was the latest at the time when then were deployed. To use a new version of a custom component, undeploy the pipelines using the component and deploy them again. To compare different versions of a component, upload a package with both versions included in the `.py` file, similar to how you would upload two components at once. Ensure each version has a unique name. After that, create multiple pipelines, each using a different component version, and compare their performance. ### Handling Non-JSON Serializable Types If your component uses an input type that's not JSON-serializable, you must implement its serialization methods: `to_dict()` and `from_dict()`. These methods define how to convert the type into a dictionary, which is needed for storage or transmission. One example is the `Secret` type. This type enhances security by preventing you from directly passing sensitive information, like API keys, into initialization parameters. Since it's not a JSON-serializable type, you must implement the `to_dict()` and `from_dict()` methods to convert it into a JSON-serializable string for proper handling. For an example of a component that uses the `Secret` type, see the Examples section below. ### Using Components In a Pipeline Once your component is in , you can add it to your pipelines using Pipeline Builder. Create or edit your pipeline as you normally would and add your custom component to it by dragging it from the Custom tab in the Component Library. Optionally, you can: - Add the initialization parameters your component requires in the `__init__()` method. For example, this custom component is initialized with the `pydantic_model` parameter: ```python from pydantic import ValidationError from typing import Optional, List from colorama import Fore from haystack import component # Define the component input parameters @component class OutputValidator: """ Validates if a JSON object complies with the provided Pydantic model. If it doesn't, this component returns an error message along with the incorrect object. """ def __init__(self, pydantic_model: pydantic.BaseModel): """ Initialize the OutputValidator component. :param pydantic_model: The Pydantic model the JSON object should comply with. """ self.pydantic_model = pydantic_model self.iteration_counter = 0 # Define the component output @component.output_types(valid_replies=List[str], invalid_replies=Optional[List[str]], error_message=Optional[str]) def run(self, replies: List[str]): """ Validate a JSON object. :param replies: The LLM output that should be validated. """ self.iteration_counter += 1 ## Try to parse the LLM's reply ## # If the LLM's reply is a valid object, return `"valid_replies"` try: output_dict = json.loads(replies[0]) self.pydantic_model.parse_obj(output_dict) print( Fore.GREEN + f"OutputValidator at Iteration {self.iteration_counter}: Valid JSON from LLM - No need for looping: {replies[0]}" ) return {"valid_replies": replies} # If the LLM's reply is corrupted or not valid, return "invalid_replies" and the "error_message" for LLM to try again except (ValueError, ValidationError) as e: print( Fore.RED + f"OutputValidator at Iteration {self.iteration_counter}: Invalid JSON from LLM - Let's try again.\n" f"Output from LLM:\n {replies[0]} \n" f"Error from OutputValidator: {e}" ) return {"invalid_replies": replies, "error_message": str(e)} ``` - Add docstrings. This is not required, but we recommend adding docstrings to explain the purpose and functionality of your component. These docstrings appear as component tooltips in Pipeline Builder and also serve as component documentation. To add a docstring, place it under the component name within triple quotes (`"""`). You can use Markdown formatting: ```python @component class ComponentName: # Add docstrings here like that: """ Description of the component. You can use Markdown formatting. """ # If your component takes parameters, add their explanations like this: def method_name(self, param1_name: Optional[type] = default_value, param2_name: Required[type] = default_value2): """ Description of what the method does :param param1_name: Description of the parameter. You can use Markdown formatting. :param param2_name: Description of the parameter. You can use Markdown formatting. """ ``` - Add other methods your component needs. ## Examples ### Components With No Parameters This is an example of a very basic component called WelcomeTextGenerator with just the `run()` method. The component takes `name` as an input parameter and returns a welcome text with the `name`, converted to upper case, and a note. ```python @component # decorator class WelcomeTextGenerator: # component name """ A component generating personal welcome message and making it upper case. Example from [Haystack documentation](https://docs.haystack.deepset.ai/docs/custom-components#extended-example). """ @component.output_types(welcome_text=str, note=str) # types of data the component outputs def run(self, name: str) -> Dict[str, str]: # parameters for the run() method, the types match the output_types (two strings) """ Generate a welcome message and make it upper case. :param name: The name of the user to include in the message. """ return { "welcome_text": ( "Hello {name}, welcome to Haystack!".format(name=name) ).upper(), "note": "welcome message is ready", } # For `name: Jane` the component will return: # {'welcome_text': "HELLO JANE, WELCOME TO HAYSTACK!", 'note':"welcome message is ready"} ``` ### Components With Initialization Parameters Here's an example of a component with initialization parameters. The component is called `OutputValidator` and is designed to validate if the JSON object an LLM generated complies with the provided Pydantic model. It's initialized with a `pydantic_model`. At runtime, it expects `replies`, which is the LLM's output to verify. It then returns the valid objects and invalid objects. If there are invalid objects, it also returns an error message: ```python from pydantic import ValidationError from typing import Optional, List from colorama import Fore from haystack import component # Define the component input parameters @component class OutputValidator: """ Validates if a JSON object complies with the provided Pydantic model. If it doesn't, this component returns an error message along with the incorrect object. """ def __init__(self, pydantic_model: pydantic.BaseModel): """ Initialize the OutputValidator component. :param pydantic_model: The Pydantic model the JSON object should comply with. """ self.pydantic_model = pydantic_model self.iteration_counter = 0 # Define the component output @component.output_types(valid_replies=List[str], invalid_replies=Optional[List[str]], error_message=Optional[str]) def run(self, replies: List[str]): """ Validate a JSON object. :param replies: The LLM output that should be validated. """ self.iteration_counter += 1 ## Try to parse the LLM's reply ## # If the LLM's reply is a valid object, return `"valid_replies"` try: output_dict = json.loads(replies[0]) self.pydantic_model.parse_obj(output_dict) print( Fore.GREEN + f"OutputValidator at Iteration {self.iteration_counter}: Valid JSON from LLM - No need for looping: {replies[0]}" ) return {"valid_replies": replies} # If the LLM's reply is corrupted or not valid, return "invalid_replies" and the "error_message" for LLM to try again except (ValueError, ValidationError) as e: print( Fore.RED + f"OutputValidator at Iteration {self.iteration_counter}: Invalid JSON from LLM - Let's try again.\n" f"Output from LLM:\n {replies[0]} \n" f"Error from OutputValidator: {e}" ) return {"invalid_replies": replies, "error_message": str(e)} ``` For more information and examples, see Haystack resources: - Examples of custom components in Haystack: [Custom Components](https://haystack.deepset.ai/integrations?type=Custom+Component). - [Generating Structured Output with Loop-Based Auto-Correction](https://haystack.deepset.ai/tutorials/28_structured_output_with_loop): An example that uses a custom component to validate JSON objects generated by an LLM. ### Components Connecting to a Third-Party Provider You can add components to integrate tools and services into . An example are the `VoyageTextEmbedder` and `VoyageDocumentEmbedder`, which are components developed by a Haystack community member to connect to Voyage AI. Using custom components, you can connect to any provider. Components that connect to third-party providers need an API key of the provider to connect to it. An example may be a generator connecting to a model provider. The easiest way to handle this is by storing the API key in an environment variable and then retrieving it in the component's `run()` method. You can also use the Secrets feature to manage your API keys in custom components. This requires adding serialization and deserialization method to your component's code. For examples and explanation, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). ### Components With Non-JSON Serializable Input Types Let's look at an example of a component using the `Secret` type. It has the necessary import statement, then the `warm_up()` method to load the API key before pipeline validation, and finally the serialization `to_dict()` and deserialization `from_dict()` methods: ```python from haystack import component, default_from_dict, default_to_dict from haystack.utils import Secret, deserialize_secrets_inplace from typing import Any, Dict @component class MyComponent: def __init__(self, model_name: str, api_key: Secret = Secret.from_env_var("ENV_VAR_NAME")): self.model_name = model_name self.api_key = api_key self.backend = None def warm_up(self): # Call api_key.resolve_value() to load the API key from the environment variable # We put the resolution in warm_up() to avoid loading the API key during pipeline validation if self.backend is None: self.backend = SomeBackend(self.model_name, self.api_key.resolve_value()) def to_dict(self) -> Dict[str, Any]: # Make sure to include any other init parameters in the to_dict method return default_to_dict( self, model_name=self.model_name, api_key=self.api_key.to_dict(), ) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MyComponent": # Make sure to use deserialize_secrets_inplace to load the Secret object init_params = data.get("init_parameters", {}) deserialize_secrets_inplace(init_params, keys=["api_key"]) return default_from_dict(cls, data) def run(self, my_input: Any): if self.backend is None: raise RuntimeError("The component wasn't warmed up. Run 'warm_up()' before calling 'run()'.") return self.backend.process(my_input) ``` For more information about how secrets work in Haystack, see [Secret Management](https://docs.haystack.deepset.ai/docs/secret-management). For details on secrets in , see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). ### Components Using Haystack Experimental Features You can use custom components to add components from the [haystack-experimental](https://github.com/deepset-ai/haystack-experimental) package to your pipelines and try them out. Bear in mind that the experimental components are not suitable for production pipelines as they're likely to change or get deprecated. For more information about haystack-experimental, see [Haystack documentation](https://github.com/deepset-ai/haystack-experimental) and [ and Haystack](/docs/getting-started/whats-deepset-cloud/deepset-cloud-and-haystack.mdx). To add an experimental component, import it and then inherit from it in you custom component code. This example adds `LLMMetadataExtractor` from the haystack-experimental package: ```python from haystack import component from haystack_experimental.components.extractors.llm_metadata_extractor import ( LLMMetadataExtractor, ) @component class ExperimentalLLMMetadataExtractor(LLMMetadataExtractor): """Haystack Experimental LLM Metadata Extractor""" ``` Save the component code, upload it to , and use it like you would any other custom component. ### Components In a Pipeline This is an example of an indexing pipeline that uses a custom component called `CharacterSplitter`. This component splits text into smaller chunks by the number of characters you specify. It takes the `split_length` parameter, accepts a list of documents as input, and returns as list of split documents. ```yaml components: # ... custom_component: # this is a custom name for your component, it's up to you init_parameters: #here you can set init parameters for your component, if you added any. Otherwise delete init_parameters. split_length: 50 type: dc_custom_component.components.splitters.character_splitter.CharacterSplitter # this is the path to your custom component; it reflects the template structure starting from the "src" directory and separated with periods. # If you changed the path, the type must reflect this. # This component's path was "./dc-component-template/src/dc_custom_component/components/splitters/character_splitter.py" pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: "intfloat/e5-base-v2" connections: - receiver: custom_component.documents # Define how to connect to your component to other components, make sure the input and output types match. sender: pptx_converter.documents - receiver: document.embedder.documents sender: custom_component.documents inputs: # Define the inputs for your pipeline files: # These components will receive files as input # ... max_loops_allowed: 100 metadata: {} ``` --- ## CSVDocumentCleaner Clean CSV documents by removing empty rows and columns. Use this component in indexing pipelines to prepare CSV data before splitting or embedding. ## Key Features - Removes entirely empty rows and columns from CSV content. - Preserves a specified number of rows from the top and columns from the left before processing. - Reattaches the preserved rows and columns to maintain their original positions in the output. - Optionally retains the original document ID. ## Configuration 1. Drag the `CSVDocumentCleaner` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the component behavior: - Set **Ignore Rows** to specify how many rows from the top of the CSV table to preserve before processing. - Set **Ignore Columns** to specify how many columns from the left to preserve before processing. - Toggle **Remove Empty Rows** to remove rows that are entirely empty. - Toggle **Remove Empty Columns** to remove columns that are entirely empty. - Toggle **Keep ID** to retain the original document ID in the output document. ## Connections `CSVDocumentCleaner` accepts a list of `Document` objects containing CSV-formatted content. It outputs cleaned `Document` objects with empty rows and columns removed. It typically receives documents from converters like `CSVToDocument` and sends cleaned documents to `CSVDocumentSplitter` or `DocumentWriter`. ## Source Code To check this component's source code, open [`csv_document_cleaner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/csv_document_cleaner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml CSVDocumentCleaner: type: haystack.components.preprocessors.csv_document_cleaner.CSVDocumentCleaner init_parameters: ignore_rows: 0 ignore_columns: 0 remove_empty_rows: true remove_empty_columns: true keep_id: false ``` ### Using the Component in an Index This example shows an index that cleans CSV documents and then writes them to a document store. ```yaml # haystack-pipeline components: CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: csv-documents-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true similarity: cosine method: mappings: settings: index.knn: true http_auth: use_ssl: verify_certs: timeout: policy: NONE CSVDocumentCleaner: type: haystack.components.preprocessors.csv_document_cleaner.CSVDocumentCleaner init_parameters: ignore_rows: 0 ignore_columns: 0 remove_empty_rows: true remove_empty_columns: true keep_id: false connections: - sender: CSVToDocument.documents receiver: CSVDocumentCleaner.documents - sender: CSVDocumentCleaner.documents receiver: DocumentWriter.documents - sender: CSVToDocument.documents receiver: CSVDocumentCleaner.documents - sender: CSVDocumentCleaner.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - CSVToDocument.sources documents: - CSVToDocument.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents containing CSV-formatted content. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of cleaned documents with empty rows and columns removed. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `ignore_rows` | int | 0 | Number of rows to ignore from the top of the CSV table before processing. | | `ignore_columns` | int | 0 | Number of columns to ignore from the left of the CSV table before processing. | | `remove_empty_rows` | bool | True | Whether to remove rows that are entirely empty. | | `remove_empty_columns` | bool | True | Whether to remove columns that are entirely empty. | | `keep_id` | bool | False | Whether to retain the original document ID in the output document. Rows and columns ignored using these parameters are preserved in the final output, meaning they are not considered when removing empty rows and columns. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents containing CSV-formatted content. | ## Related Information - [CSVDocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/CSVDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CSVDocumentSplitter Split CSV documents into sub-tables based on empty rows or columns. Use this component in indexing pipelines to break large CSV files into smaller, more manageable chunks before embedding. ## Key Features - Splits CSV documents into smaller sub-tables using empty row or column delimiters. - Supports threshold mode: splits on consecutive empty rows or columns that exceed a configurable threshold. - Supports row-wise mode: splits each row into a separate sub-table document. - Tracks metadata for each split, including source document ID, starting row and column index, and split order. ## Configuration 1. Drag the `CSVDocumentSplitter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Choose a **Split Mode**: `threshold` to split on consecutive empty rows or columns, or `row-wise` to split each row into a separate document. - Set **Row Split Threshold** to the minimum number of consecutive empty rows required to trigger a split (used in threshold mode). - Set **Column Split Threshold** to the minimum number of consecutive empty columns required to trigger a split (used in threshold mode). - Set **Read CSV Kwargs** to pass additional options to `pandas.read_csv`, such as custom delimiters or encodings. ## Connections `CSVDocumentSplitter` accepts a list of `Document` objects containing CSV-formatted content. It outputs a list of `Document` objects, each representing an extracted sub-table from the original CSV. Each output document includes `source_id`, `row_idx_start`, `col_idx_start`, and `split_id` metadata fields. It typically receives documents from `CSVDocumentCleaner` or directly from converters like `CSVToDocument`, and sends split documents to embedders or `DocumentWriter`. ## Source Code To check this component's source code, open [`csv_document_splitter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/csv_document_splitter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml CSVDocumentSplitter: type: haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter init_parameters: row_split_threshold: 2 column_split_threshold: 2 split_mode: threshold ``` ### Using the Component in an Index This example shows an index that cleans and splits CSV documents before embedding and storing them. ```yaml # haystack-pipeline components: CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: csv-documents-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true similarity: cosine method: mappings: settings: index.knn: true http_auth: use_ssl: verify_certs: timeout: policy: NONE CSVDocumentSplitter: type: haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter init_parameters: row_split_threshold: 2 column_split_threshold: 2 read_csv_kwargs: split_mode: threshold CSVDocumentCleaner: type: haystack.components.preprocessors.csv_document_cleaner.CSVDocumentCleaner init_parameters: ignore_rows: 0 ignore_columns: 0 remove_empty_rows: true remove_empty_columns: true keep_id: false connections: - sender: CSVToDocument.documents receiver: CSVDocumentCleaner.documents - sender: CSVDocumentCleaner.documents receiver: CSVDocumentSplitter.documents - sender: CSVDocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - CSVToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Documents containing CSV-formatted content. Each document is assumed to contain one or more tables separated by empty rows or columns. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents, each representing an extracted sub-table from the original CSV. Document metadata includes `source_id`, `row_idx_start`, `col_idx_start`, and `split_id`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `row_split_threshold` | Optional[int] | 2 | The minimum number of consecutive empty rows required to trigger a split. | | `column_split_threshold` | Optional[int] | 2 | The minimum number of consecutive empty columns required to trigger a split. | | `read_csv_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments to pass to `pandas.read_csv`. By default, the component uses `header=None`, `skip_blank_lines=False` to preserve blank lines, and `dtype=object` to prevent type inference. See the [pandas documentation](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html) for more information. | | `split_mode` | SplitMode | threshold | If `threshold`, splits the document based on consecutive empty rows or columns exceeding the threshold. If `row-wise`, splits each row into a separate sub-table. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Documents containing CSV-formatted content. Each document is assumed to contain one or more tables separated by empty rows or columns. | ## Related Information - [CSVDocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/CSVDocumentCleaner.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DeepsetDocumentMetadataPreProcessor Process and transform document metadata by replacing metadata keys or converting metadata fields into document content. ## Key Features - Replaces metadata keys with new names across all documents, for example, normalizing inconsistent keys from different sources. - Converts selected metadata fields into document content to improve full-text search. - Lets you specify which metadata fields to convert, or converts all fields if none are specified. - Adds a configurable prefix to each line of converted metadata. - Includes a debug mode for inspecting the component's behavior. ## Configuration 1. Drag the `DeepsetDocumentMetadataPreProcessor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Replace Fields** to define metadata key replacements. For example, `presiding_officer: judge` renames the `presiding_officer` key to `judge`. - Toggle **Convert Meta to Content** to convert metadata fields into document content. - Set **Meta Fields to Convert** to specify which metadata fields to convert. If left empty, all metadata fields are converted. - Set **Line Prefix** to add a prefix to each line of converted metadata (default: `- `). - Toggle **Debug** to display debugging information. ## Connections `DeepsetDocumentMetadataPreProcessor` accepts a list of `Document` objects and outputs processed `Document` objects with updated metadata or content. It works with any component that outputs documents and accepts documents as input, such as converters, rankers, or retrievers. ## Usage Examples ### Basic Configuration ```yaml DeepsetDocumentMetadataPreProcessor: type: deepset_cloud_custom_nodes.preprocessors.document_metadata_preprocessor.DeepsetDocumentMetadataPreProcessor init_parameters: replace_fields: - judge_name: judge - presiding_officer: judge convert_meta_to_content: false line_prefix: '- ' debug: false ``` ### Using the Component in an Index #### Replacing Metadata Keys In this index, `DeepsetDocumentMetadataPreProcessor` normalizes all metadata keys into a unified key. Such index could work on legal documents from different sources, such as courts, law firms, or regulation bodies that often use inconsistent metadata keys. Some documents use `judge_name`, others `presiding_officer`, while we want a key called `judge`. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE DeepsetDocumentMetadataPreProcessor: type: deepset_cloud_custom_nodes.preprocessors.document_metadata_preprocessor.DeepsetDocumentMetadataPreProcessor init_parameters: replace_fields: - judge_name: judge - presiding_officer: judge convert_meta_to_content: false meta_fields_to_convert: line_prefix: '- ' debug: false connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: splitter.documents receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents - sender: joiner.documents receiver: DeepsetDocumentMetadataPreProcessor.documents - sender: DeepsetDocumentMetadataPreProcessor.documents receiver: splitter.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` #### Converting Metadata Into content This example converts the metadata containing the judge name into the document content. This may be a good solution for full text search. The component adds the `judge: judge_name` to the document content while retaining them in the metadata as well: ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE DeepsetDocumentMetadataPreProcessor: type: deepset_cloud_custom_nodes.preprocessors.document_metadata_preprocessor.DeepsetDocumentMetadataPreProcessor init_parameters: replace_fields: "\n" convert_meta_to_content: true meta_fields_to_convert: judge line_prefix: '- ' debug: false connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: splitter.documents receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents - sender: joiner.documents receiver: DeepsetDocumentMetadataPreProcessor.documents - sender: DeepsetDocumentMetadataPreProcessor.documents receiver: splitter.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | Optional[List[Document]] | List of Documents to process. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Processed documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `replace_fields` | Optional[dict] | None | Dictionary with the metadata fields to replace. It must contain the names of the fields to replace and their new values. For example: `presiding_officer: judge` replaces metadata fields called "presiding_officer" with "judge". | | `convert_meta_to_content` | Optional[bool] | False | Converts metadata to document content. | | `meta_fields_to_convert` | Optional[List[str]] | None | List of metadata fields to convert to content. If `None`, all metadata fields are converted. | | `line_prefix` | str | - | Prefix to add to each line of the converted metadata. | | `debug` | bool | False | Displays debugging information for the component. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | Optional[List[Document]] | List of Documents to process. | --- ## DocumentCleaner Clean the text in documents by removing whitespaces, empty lines, headers, footers, and more. Use this component in indexing pipelines to prepare documents for further processing by LLMs or embedders. ## Key Features - Removes empty lines and extra whitespaces. - Removes repeated substrings such as headers and footers across pages. - Removes specific substrings or text matching a regular expression. - Normalizes Unicode characters (NFC, NFKC, NFD, or NFKD). - Converts text to ASCII only, removing accents and non-ASCII characters. - Optionally retains the original document ID. ## Configuration 1. Drag the `DocumentCleaner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Toggle **Remove Empty Lines** to remove empty lines from the document. - Toggle **Remove Extra Whitespaces** to remove extra whitespaces from the document. - Toggle **Remove Repeated Substrings** to remove repeated headers and footers from pages. Pages must be separated by a form feed character `\f`, which is supported by `TextFileToDocument` and `AzureOCRDocumentConverter`. - Set **Remove Substrings** to specify a list of strings to remove from the document. - Set **Remove Regex** to specify a regular expression pattern whose matches are removed. - Set **Unicode Normalization** to apply Unicode normalization to the text. - Toggle **ASCII Only** to convert text to ASCII, removing accents and other non-ASCII characters. - Toggle **Keep ID** to retain the original document ID. ## Connections `DocumentCleaner` accepts a list of `Document` objects and outputs cleaned `Document` objects. It typically receives documents from converters like `TextFileToDocument`, `PDFMinerToDocument`, or `AzureOCRDocumentConverter`, and sends cleaned documents to `DocumentSplitter` for chunking or directly to document embedders. ## Source Code To check this component's source code, open [`document_cleaner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/document_cleaner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentCleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false keep_id: false ascii_only: false ``` ### Using the Component in an Index This example shows a typical indexing pipeline where `DocumentCleaner` cleans documents after conversion and before splitting. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentCleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false remove_substrings: remove_regex: keep_id: false unicode_normalization: ascii_only: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: documents-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentCleaner.documents - sender: DocumentCleaner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents to clean. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of cleaned documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `remove_empty_lines` | bool | True | If `True`, removes empty lines. | | `remove_extra_whitespaces` | bool | True | If `True`, removes extra whitespaces. | | `remove_repeated_substrings` | bool | False | If `True`, removes repeated substrings (headers and footers) from pages. Pages must be separated by a form feed character "\f", which is supported by `TextFileToDocument` and `AzureOCRDocumentConverter`. | | `remove_substrings` | Optional[List[str]] | None | List of substrings to remove from the text. | | `remove_regex` | Optional[str] | None | Regex to match and replace substrings by "". | | `keep_id` | bool | False | If `True`, keeps the IDs of the original documents. | | `unicode_normalization` | Optional[Literal['NFC', 'NFKC', 'NFD', 'NFKD']] | None | Unicode normalization form to apply to the text. Note: This will run before any other steps. | | `ascii_only` | bool | False | Whether to convert the text to ASCII only. Will remove accents from characters and replace them with ASCII characters. Other non-ASCII characters will be removed. Note: This will run before any pattern matching or removal. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents to clean. | ## Related Information - [DocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentSplitter.mdx) - [DocumentPreprocessor](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentPreprocessor.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DocumentPreprocessor A SuperComponent that splits and cleans documents in a single step. It combines `DocumentSplitter` and `DocumentCleaner` into one component for use in indexing pipelines. ## Key Features - Splits documents into smaller chunks using configurable units such as words, sentences, pages, or paragraphs. - Cleans documents by removing empty lines, extra whitespaces, and repeated substrings like headers and footers. - Supports overlapping splits to preserve context across chunks. - Respects sentence boundaries when splitting by word. - Supports custom splitting functions. ## Configuration 1. Drag the `DocumentPreprocessor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Choose a **Split By** unit: `word`, `sentence`, `passage`, `page`, `line`, or `function`. - Set **Split Length** to the maximum number of units in each chunk. - Set **Split Overlap** to the number of overlapping units between consecutive chunks. - Toggle **Remove Empty Lines** to remove empty lines from the document. - Toggle **Remove Extra Whitespaces** to remove extra whitespaces. - Set **Split Threshold** to define the minimum number of units per chunk. Chunks smaller than this threshold are merged with the previous chunk. - Toggle **Respect Sentence Boundary** to avoid splitting in the middle of a sentence when splitting by word. - Set **Language** for the NLTK sentence tokenizer (default: `en`). - Toggle **Remove Repeated Substrings** to remove repeated headers and footers across pages. - Toggle **Keep ID** to retain the original document IDs. - Set **Remove Substrings** to specify a list of strings to remove. - Set **Remove Regex** to specify a regular expression pattern whose matches are removed. - Set **Unicode Normalization** to apply Unicode normalization. - Toggle **ASCII Only** to convert text to ASCII only. ## Connections `DocumentPreprocessor` accepts a list of `Document` objects and outputs processed `Document` objects. It's typically used in indexes between a document converter and a document embedder, or before `DocumentWriter`. ## Source Code To check this component's source code, open [`document_preprocessor.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/document_preprocessor.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentPreprocessor: type: haystack.components.preprocessors.document_preprocessor.DocumentPreprocessor init_parameters: split_by: word split_length: 200 split_overlap: 30 respect_sentence_boundary: true language: en remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false ``` ### In an Index This index pipeline uses `DocumentPreprocessor` to split and clean documents before embedding and writing them to a Document Store: ```yaml # haystack-pipeline components: MultiFileConverter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 DocumentPreprocessor: type: haystack.components.preprocessors.document_preprocessor.DocumentPreprocessor init_parameters: split_by: word split_length: 200 split_overlap: 30 respect_sentence_boundary: true language: en remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false SentenceTransformersDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 normalize_embeddings: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: OVERWRITE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' embedding_dim: 768 create_index: true connections: - sender: MultiFileConverter.documents receiver: DocumentPreprocessor.documents - sender: DocumentPreprocessor.documents receiver: SentenceTransformersDocumentEmbedder.documents - sender: SentenceTransformersDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 inputs: files: - MultiFileConverter.sources ``` In this example: 1. `MultiFileConverter` converts uploaded files into documents. 2. `DocumentPreprocessor` splits documents into chunks of 200 words with 30-word overlap, respecting sentence boundaries. It also removes empty lines and extra whitespace. 3. `SentenceTransformersDocumentEmbedder` generates embeddings for the processed documents. 4. `DocumentWriter` writes the embedded documents to OpenSearch. ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents to process. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Processed list of documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: **Splitter Parameters:** | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `split_by` | Literal['function', 'page', 'passage', 'period', 'word', 'line', 'sentence'] | word | The unit of splitting. | | `split_length` | int | 250 | The maximum number of units (words, lines, pages, etc.) in each split. | | `split_overlap` | int | 0 | The number of overlapping units between consecutive splits. | | `split_threshold` | int | 0 | The minimum number of units per split. If a split is smaller, it's merged with the previous split. | | `splitting_function` | Optional[Callable] | None | A custom function for splitting if `split_by="function"`. | | `respect_sentence_boundary` | bool | False | If True, splits by words but tries not to break inside a sentence. | | `language` | str | en | Language used by the sentence tokenizer. | | `use_split_rules` | bool | True | Whether to apply additional splitting heuristics for the sentence splitter. | | `extend_abbreviations` | bool | True | Whether to extend the sentence splitter with curated abbreviations for certain languages. | **Cleaner Parameters:** | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `remove_empty_lines` | bool | True | If True, removes empty lines. | | `remove_extra_whitespaces` | bool | True | If True, removes extra whitespaces. | | `remove_repeated_substrings` | bool | False | If True, removes repeated substrings like headers/footers across pages. | | `keep_id` | bool | False | If True, keeps the original document IDs. | | `remove_substrings` | Optional[List[str]] | None | A list of strings to remove from the document content. | | `remove_regex` | Optional[str] | None | A regex pattern whose matches are removed from the document content. | | `unicode_normalization` | Optional[Literal['NFC', 'NFKC', 'NFD', 'NFKD']] | None | Unicode normalization form to apply to the text. | | `ascii_only` | bool | False | If True, converts text to ASCII only. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents to process. | ## Related Information - [DocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentCleaner.mdx) - [DocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DocumentSplitter Split long documents into smaller chunks. Use this component in your indexes to prepare data for search. ## Key Features - Splits documents by word, sentence, passage, page, line, or a custom function. - Supports configurable chunk size and overlap between chunks. - Optionally respects sentence boundaries when splitting by word. - Adds metadata to each split, including source document ID, page number, and split order. - Merges very small splits with the previous chunk using a configurable threshold. ## Configuration 1. Drag the `DocumentSplitter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Choose a **Split By** unit: `word`, `sentence`, `passage`, `page`, `line`, or `function`. - Set **Split Length** to the maximum number of units in each chunk. - Set **Split Overlap** to the number of overlapping units between consecutive chunks. - Set **Split Threshold** to define the minimum number of units per chunk. Chunks smaller than this value are merged with the previous chunk. - Set **Splitting Function** if you chose `function` as the split unit. The function must accept a string and return a list of strings. - Toggle **Respect Sentence Boundary** to avoid splitting in the middle of a sentence when splitting by word. - Set **Language** for the NLTK sentence tokenizer (default: `en`). - Toggle **Use Split Rules** to apply additional splitting heuristics for sentence splitting. - Toggle **Extend Abbreviations** to improve sentence splitting accuracy for English and German. - Toggle **Skip Empty Documents** to skip documents with empty content. ## Connections `DocumentSplitter` accepts a list of `Document` objects and outputs a list of split `Document` objects. Each output document includes `source_id` and `page_number` metadata fields. It typically receives documents from converters or `DocumentCleaner`, and sends split documents to embedders like `SentenceTransformersDocumentEmbedder` or to `DocumentWriter`. ## Source Code To check this component's source code, open [`document_splitter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/document_splitter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 20 split_threshold: 0 respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true ``` ### Using the Component in an Index This example shows a typical index where `DocumentSplitter` chunks documents after cleaning and before embedding. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentCleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 20 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true SentenceTransformersDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: documents-index max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false create_index: true similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentCleaner.documents - sender: DocumentCleaner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: SentenceTransformersDocumentEmbedder.documents - sender: SentenceTransformersDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents to split. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents with split texts. Each document includes `source_id` and `page_number` metadata fields. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `split_by` | Literal['function', 'page', 'passage', 'period', 'word', 'line', 'sentence'] | word | The unit for splitting your documents. Choose from: `word` for splitting by spaces (" "), `period` for splitting by periods ("."), `page` for splitting by form feed ("\f"), `passage` for splitting by double line breaks ("\n\n"), `line` for splitting each line ("\n"), or `sentence` for splitting by NLTK sentence tokenizer. | | `split_length` | int | 200 | The maximum number of units in each split. | | `split_overlap` | int | 0 | The number of overlapping units for each split. | | `split_threshold` | int | 0 | The minimum number of units per split. If a split has fewer units than the threshold, it's attached to the previous split. | | `splitting_function` | Optional[Callable[[str], List[str]]] | None | Necessary when `split_by` is set to "function". This is a function which must accept a single `str` as input and return a `list` of `str` as output, representing the chunks after splitting. | | `respect_sentence_boundary` | bool | False | Choose whether to respect sentence boundaries when splitting by "word". If True, uses NLTK to detect sentence boundaries, ensuring splits occur only between sentences. | | `language` | Language | en | Choose the language for the NLTK tokenizer. The default is English ("en"). | | `use_split_rules` | bool | True | Choose whether to use additional split rules when splitting by `sentence`. | | `extend_abbreviations` | bool | True | Choose whether to extend NLTK's PunktTokenizer abbreviations with a list of curated abbreviations, if available. This is currently supported for English ("en") and German ("de"). | | `skip_empty_documents` | bool | True | Choose whether to skip documents with empty content. Set to `False` when downstream components in the Pipeline (like `LLMDocumentContentExtractor`) can extract text from non-textual documents. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents to split. | ## Related Information - [DocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentCleaner.mdx) - [DocumentPreprocessor](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentPreprocessor.mdx) - [HierarchicalDocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/HierarchicalDocumentSplitter.mdx) - [RecursiveDocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/RecursiveDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## HierarchicalDocumentSplitter Split documents into different block sizes, building a hierarchical tree structure. Use this component in indexes to enable advanced auto-merging retrieval, where you retrieve small, specific chunks and can expand to larger parent chunks for more context. ## Key Features - Splits documents into multiple block sizes, producing a hierarchy from large to small chunks. - Builds a parent-child relationship between chunks, where smaller chunks are children of larger ones. - Supports splitting by word, sentence, page, or passage. - Supports overlapping splits to preserve context across chunks. - Works with `AutoMergingRetriever` in query pipelines to merge child documents back into parent context at query time. ## Configuration 1. Drag the `HierarchicalDocumentSplitter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set **Block Sizes** to define the set of chunk sizes to split the document into. For example, `[512, 256, 128]` creates three levels of chunks in descending order. 4. Go to the **Advanced** tab to configure additional settings: - Choose a **Split By** unit: `word`, `sentence`, `page`, or `passage`. - Set **Split Overlap** to the number of overlapping units between consecutive chunks. ## Connections `HierarchicalDocumentSplitter` accepts a list of `Document` objects and outputs a list of hierarchical `Document` objects with parent-child relationships. It typically receives documents from converters or `DocumentCleaner`, and sends split documents to embedders or `DocumentWriter`. Use it together with `AutoMergingRetriever` in query pipelines to leverage the hierarchical structure. ## Source Code To check this component's source code, open [`hierarchical_document_splitter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/hierarchical_document_splitter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HierarchicalDocumentSplitter: type: haystack.components.preprocessors.hierarchical_document_splitter.HierarchicalDocumentSplitter init_parameters: block_sizes: - 512 - 256 - 128 split_overlap: 0 split_by: word ``` ### Using the Component in an Index This example shows an indexing pipeline using hierarchical splitting with block sizes of 512, 256, and 128 words. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentCleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true HierarchicalDocumentSplitter: type: haystack.components.preprocessors.hierarchical_document_splitter.HierarchicalDocumentSplitter init_parameters: block_sizes: - 512 - 256 - 128 split_overlap: 0 split_by: word SentenceTransformersDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 batch_size: 32 progress_bar: true normalize_embeddings: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: hierarchical-documents-index max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false create_index: true similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentCleaner.documents - sender: DocumentCleaner.documents receiver: HierarchicalDocumentSplitter.documents - sender: HierarchicalDocumentSplitter.documents receiver: SentenceTransformersDocumentEmbedder.documents - sender: SentenceTransformersDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents to split into hierarchical blocks. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of hierarchical documents with parent-child relationships. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `block_sizes` | Set[int] | | Set of block sizes to split the document into. The blocks are split in descending order. | | `split_overlap` | int | 0 | The number of overlapping units for each split. | | `split_by` | Literal['word', 'sentence', 'page', 'passage'] | word | The unit for splitting your documents. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents to split into hierarchical blocks. | ## Related Information - [DocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentSplitter.mdx) - [DocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentCleaner.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## RecursiveDocumentSplitter Recursively chunk text into smaller pieces using a list of separators. This approach creates more semantically meaningful chunks compared to fixed-size splitting. ## Key Features - Splits text recursively using an ordered list of separators, from most general to most specific. - Keeps chunks within the configured size limit, and re-splits larger chunks using the next separator. - Supports splitting by word, character, or token count. - Includes built-in sentence-aware splitting using NLTK. - Uses default separators (paragraph, sentence, line, word) if none are specified. ## Configuration 1. Drag the `RecursiveDocumentSplitter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Split Length** to the maximum chunk size. - Set **Split Overlap** to the number of units to overlap between consecutive chunks. - Choose a **Split Unit**: `word`, `char`, or `token`. - Set **Separators** to define an ordered list of separator strings. Use `"sentence"` as a separator value to enable sentence-aware splitting. - Set **Sentence Splitter Params** to pass optional parameters to the NLTK sentence tokenizer. ## Connections `RecursiveDocumentSplitter` accepts a list of `Document` objects and outputs a list of `Document` objects with smaller text chunks. It typically receives documents from converters or `DocumentCleaner`, and sends split documents to embedders or `DocumentWriter`. ## Source Code To check this component's source code, open [`recursive_splitter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/recursive_splitter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml RecursiveDocumentSplitter: type: haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter init_parameters: split_length: 200 split_overlap: 20 split_unit: word separators: - "\n\n" - sentence - "\n" - ' ' ``` ### Using the Component in an Index This example shows an index using recursive splitting with custom separators. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentCleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true RecursiveDocumentSplitter: type: haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter init_parameters: split_length: 200 split_overlap: 20 split_unit: word separators: - "\n\n" - sentence - "\n" - " " sentence_splitter_params: SentenceTransformersDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 batch_size: 32 progress_bar: true normalize_embeddings: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: documents-index max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false create_index: true similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentCleaner.documents - sender: DocumentCleaner.documents receiver: RecursiveDocumentSplitter.documents - sender: RecursiveDocumentSplitter.documents receiver: SentenceTransformersDocumentEmbedder.documents - sender: SentenceTransformersDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents to split. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents with smaller chunks of text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `split_length` | int | 200 | The maximum length of each chunk by default in words, but can be in characters or tokens. See the `split_units` parameter. | | `split_overlap` | int | 0 | The number of characters to overlap between consecutive chunks. | | `split_unit` | Literal['word', 'char', 'token'] | word | The unit of the split_length parameter. It can be either "word", "char", or "token". If "token" is selected, the text will be split into tokens using the tiktoken tokenizer (o200k_base). | | `separators` | Optional[List[str]] | None | An optional list of separator strings to use for splitting the text. The string separators will be treated as regular expressions unless the separator is "sentence", in that case the text will be split into sentences using a custom sentence tokenizer based on NLTK. If no separators are provided, the default separators ["\n\n", "sentence", "\n", " "] are used. | | `sentence_splitter_params` | Optional[Dict[str, Any]] | None | Optional parameters to pass to the sentence tokenizer. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents to split. | ## Related Information - [DocumentSplitter](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentSplitter.mdx) - [DocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentCleaner.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## TextCleaner Clean text strings by removing patterns, converting to lowercase, or removing punctuation and numbers. Unlike `DocumentCleaner`, which works with `Document` objects, `TextCleaner` operates on plain text strings. ## Key Features - Removes substrings matching regular expressions. - Converts all text to lowercase. - Removes punctuation from text. - Removes numerical digits from text. ## Configuration 1. Drag the `TextCleaner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Remove Regexps** to specify a list of regular expression patterns. The component removes all matching substrings from the text. - Toggle **Convert to Lowercase** to convert all characters to lowercase. - Toggle **Remove Punctuation** to remove punctuation from the text. - Toggle **Remove Numbers** to remove numerical digits from the text. ## Connections `TextCleaner` accepts a list of text strings and outputs a list of cleaned text strings. It typically receives generated text from generators and sends cleaned text to evaluation components for comparison. It connects with any component that outputs text strings. ## Source Code To check this component's source code, open [`text_cleaner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/preprocessors/text_cleaner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TextCleaner: type: haystack.components.preprocessors.text_cleaner.TextCleaner init_parameters: convert_to_lowercase: true remove_punctuation: false remove_numbers: false ``` ### Using the Component in a Pipeline This example shows a pipeline that cleans generated answers before evaluation. ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' embedding_dim: 384 return_embedding: false create_index: true similarity: cosine top_k: 5 text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the question based on the context. Context: {% for doc in documents %}{{ doc.content }}{% endfor %} Question: {{ question }} Answer: generator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o-mini TextCleaner: type: haystack.components.preprocessors.text_cleaner.TextCleaner init_parameters: remove_regexps: convert_to_lowercase: true remove_punctuation: false remove_numbers: false connections: - sender: text_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: TextCleaner.texts max_runs_per_component: 100 metadata: {} inputs: query: - text_embedder.text - prompt_builder.question outputs: answers: TextCleaner.texts ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `texts` | List[str] | List of strings to clean. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `texts` | List[str] | List of cleaned text strings. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `remove_regexps` | Optional[List[str]] | None | A list of regex patterns to remove matching substrings from the text. | | `convert_to_lowercase` | bool | False | If `True`, converts all characters to lowercase. | | `remove_punctuation` | bool | False | If `True`, removes punctuation from the text. | | `remove_numbers` | bool | False | If `True`, removes numerical digits from the text. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `texts` | List[str] | List of strings to clean. | ## Related Information - [DocumentCleaner](/docs/reference/pipeline-components/data-processing/clean-and-split/DocumentCleaner.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## Clean & Split Overview # Clean & Split Group Components in this group help you prepare raw documents for retrieval. Use them to remove boilerplate and noise, normalize content, and split large documents into smaller chunks that are easier to embed, index, and retrieve. This subgroup is especially useful when your inputs vary in format or quality, or when you want more control over chunk size and boundaries (for example, splitting by structure, recursively, or by CSV rows). Well-chosen cleaning and splitting improves retrieval quality and reduces wasted context in downstream steps. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## CSVToDocument Convert CSV files to documents your pipeline can query. You can choose between creating one document per file or one document per row. ## Key Features - Two conversion modes: file mode (one document per CSV file) and row mode (one document per row). - Configurable encoding with UTF-8 as default. - Optional metadata attachment to resulting documents. - Configurable delimiter and quote character for row mode parsing. ## Configuration 1. Drag the `CSVToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Encoding** for the CSV files. The default is UTF-8. - Set the **Conversion Mode**: choose `file` to create one document per CSV file, or `row` to create one document per row. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. - If using row mode, set the **Delimiter** and **Quote Character** for CSV parsing. ## Connections `CSVToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives CSV files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`csv.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/csv.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false ``` ### Using the Component in an Index In this index, `CSVToDocument` receives CSV files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/csv - application/pdf additional_mimetypes: raise_on_failure: false PyPDFToDocument: type: haystack.components.converters.pypdf.PyPDFToDocument init_parameters: extraction_mode: plain plain_mode_orientations: - 0 - 90 - 180 - 270 plain_mode_space_width: 200 layout_mode_space_vertically: true layout_mode_scale_weight: 1.25 layout_mode_strip_rotated: true layout_mode_font_height_weight: 1 store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true skip_empty_documents: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: FileTypeRouter.text/csv receiver: CSVToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PyPDFToDocument.sources - sender: CSVToDocument.documents receiver: DocumentJoiner.documents - sender: PyPDFToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, the length of the list must match the number of sources, because the two lists are zipped. If `sources` contains ByteStream objects, their `meta` is added to the output documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Created documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `encoding` | str | utf-8 | The encoding of the CSV files to convert. If the encoding is specified in the metadata of a source ByteStream, it overrides this value. | | `store_full_path` | bool | False | If True, the full file path is stored in the metadata of the document. If False, only the file name is stored. | | `conversion_mode` | Literal["file", "row"] | file | Conversion mode. Use `file` to create one Document per CSV file with raw CSV text as content. Use `row` to convert each CSV row to its own Document (requires `content_column` in `run()`). | | `delimiter` | str | , | CSV delimiter used when parsing in row mode. Must be a single character. | | `quotechar` | str | " | CSV quote character used when parsing in row mode. Must be a single character. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `content_column` | Optional[str] | None | Required when `conversion_mode="row"`. The column name whose values become `Document.content` for each row. The column must exist in the CSV header. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output documents. | --- ## DOCXToDocument Convert DOCX files to documents your pipeline can query, with configurable formatting for tables and links. `DOCXToDocument` uses the `python-docx` library to extract text from DOCX files. Note that it doesn't preserve page breaks from the original document. ## Key Features - Configurable table output format: CSV (default) or Markdown. - Configurable link output format: plain text, Markdown, or no links. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `DOCXToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Table Format** to control how tables are extracted: `csv` (default) or `markdown`. - Set the **Link Format** to control how hyperlinks appear in the extracted text: `none` (default, text only), `markdown` (for `[text](url)`), or `plain` (for `text (url)`). - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `DOCXToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives DOCX files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`docx.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/docx.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown ``` ### Using the Component in an Index In this index, `DOCXToDocument` receives DOCX files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - application/vnd.openxmlformats-officedocument.wordprocessingml.document text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: document_embedder.documents receiver: writer.documents - sender: splitter.documents receiver: document_embedder.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the converted documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Created documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `table_format` | Union[str, DOCXTableFormat] | DOCXTableFormat.CSV | The format for table output. Can be either DOCXTableFormat.MARKDOWN, DOCXTableFormat.CSV, "markdown", or "csv". | | `link_format` | Union[str, DOCXLinkFormat] | DOCXLinkFormat.NONE | The format for link output. Can be either: DOCXLinkFormat.MARKDOWN or "markdown" to get `[text](url)`, DOCXLinkFormat.PLAIN or "plain" to get `text (url)`, DOCXLinkFormat.NONE or "none" to get text without links. | | `store_full_path` | bool | False | If True, the full file path is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists are zipped. If `sources` contains ByteStream objects, their `meta` is added to the output Documents. | --- ## DeepsetCSVRowsToDocumentsConverter Read CSV files from various sources and convert each row into Haystack documents. `DeepsetCSVRowsToDocumentsConverter` reads a CSV file and converts each row into a `Document` object, using one column as the document's main content. All other columns are added to the document's metadata. ## Key Features - Converts each CSV row into a separate document — useful for pre-chunked datasets. - Configurable content column to select which column becomes the document content. - All remaining columns are automatically stored in document metadata. - Supports UTF-8 encoding by default with configurable encoding. ## Configuration 1. Drag the `DeepsetCSVRowsToDocumentsConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Content Column** to specify which CSV column to use as the document content. The default is `content`. - Set the **Encoding** for the CSV files. The default is UTF-8. ## Connections `DeepsetCSVRowsToDocumentsConverter` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects, one per CSV row. Because the output documents are already one-row chunks, you can bypass a document splitter and connect directly to an embedder. It typically connects with: - `FileTypeRouter`: receives CSV files routed by MIME type. - `SentenceTransformersDocumentEmbedder` or other embedders: sends documents directly for embedding. ## Usage Examples ### Basic Configuration ```yaml DeepsetCSVRowsToDocumentsConverter: type: deepset_cloud_custom_nodes.converters.csv_rows_to_documents.DeepsetCSVRowsToDocumentsConverter init_parameters: content_column: content encoding: utf-8 ``` ### Using the Component in a Pipeline This is an example of an index that processes multiple file types. It starts with `FilesInput` followed by `file_classifier` (`FileTypeRouter`) which classifies files by type and sends them to an appropriate converter. `DeepsetCSVRowsToDocumentsConverter` receives CSV files from `file_classifier` (`FileTypeRouter`) and outputs a list of pre-chunked documents. Since these documents are already chunked, they bypass the splitter (`DeepsetDocumentSplitter`) and go directly to the `document_embedder` (`SentenceTransformersDocumentEmbedder`) and finally to the writer (`DocumentWriter`), which writes them into the document store. YAML configuration: ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/markdown - text/html - text/csv markdown_converter: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: {} html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: txt target_language: include_tables: true include_links: false document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE DeepsetCSVRowsToDocumentsConverter: type: deepset_cloud_custom_nodes.converters.csv_rows_to_documents.DeepsetCSVRowsToDocumentsConverter init_parameters: content_column: content encoding: utf-8 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true skip_empty_documents: true connections: - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: DeepsetCSVRowsToDocumentsConverter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents - sender: file_classifier.text/csv receiver: DeepsetCSVRowsToDocumentsConverter.sources - sender: markdown_converter.documents receiver: DocumentSplitter.documents - sender: html_converter.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: document_embedder.documents metadata: {} inputs: files: - file_classifier.sources max_runs_per_component: 100 ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of CSV file paths (str or Path) or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. Can be a single dict or a list of dicts. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Haystack Documents, one per CSV row. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `content_column` | str | content | Name of the column to use as content when processing the CSV file. | | `encoding` | str | utf-8 | Encoding type to use when reading the files. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of CSV file paths (str or Path) or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. Can be a single dict or a list of dicts. | --- ## DocumentToImageContent Extract visual content from images or PDFs and convert them into `ImageContent` objects you can use for multimodal AI tasks. `DocumentToImageContent` processes documents whose metadata contains file paths pointing to image or PDF files. For images, it encodes the file directly. For PDFs, it extracts the page specified by the `page_number` metadata key and converts it to an image. ## Key Features - Extracts and base64-encodes images from image files or specific PDF pages. - Accepts documents with file path metadata — no raw file input needed. - Optional image resizing to reduce file size while preserving aspect ratio. - Configurable detail level for optimization with OpenAI vision models. - Returns `None` for documents that cannot be processed, without failing the pipeline. ## Configuration 1. Drag the `DocumentToImageContent` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **File Path Meta Field** to specify which metadata key in each Document contains the file path. The default is `file_path`. - Optionally, set the **Root Path** to a base directory. File paths in document metadata are resolved relative to this path. - Set the **Detail** level for images (`auto`, `high`, or `low`). This is passed to the created `ImageContent` objects and is only supported by OpenAI. - Set the **Size** to resize images to the specified dimensions (width, height) while maintaining aspect ratio. ## Connections `DocumentToImageContent` accepts a list of `Document` objects through its `documents` input. It outputs a list of `ImageContent` objects (or `None` for documents that couldn't be processed). It typically connects with: - Retrievers: receives documents from a retriever that found relevant image or PDF references. - `ChatPromptBuilder`: sends extracted `ImageContent` objects to include in multimodal prompts. ## Source Code To check this component's source code, open [`document_to_image.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/image/document_to_image.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml document_to_image: type: haystack.components.converters.image.document_to_image.DocumentToImageContent init_parameters: file_path_meta_field: file_path root_path: /data/images detail: high size: - 512 - 512 ``` ### Pipeline Example Here's an example of `DocumentToImageContent` used in a query pipeline. It extracts images from documents and sends them to a `ChatPromptBuilder` that includes them in the chat message for the model. Note that the model must support multimodal input. ```yaml # haystack-pipeline components: document_to_image: type: haystack.components.converters.image.document_to_image.DocumentToImageContent init_parameters: file_path_meta_field: file_path root_path: "/data/images" detail: high size: [512, 512] prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: "- _role: user\n _content:\n - text: 'Analyze the following images and answer this question: {{question}}'\n 'image: {{images}}'\n" generator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-4-vision-preview OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' truncate: normalize_embeddings: true timeout: backend_kwargs: DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: pattern: reference_pattern: extract_xml_tags: connections: - sender: document_to_image.image_contents receiver: prompt_builder.images - sender: prompt_builder.prompt receiver: generator.prompt - sender: OpenSearchEmbeddingRetriever.documents receiver: document_to_image.documents - sender: DeepsetNvidiaTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding - sender: generator.replies receiver: DeepsetAnswerBuilder.replies inputs: query: - prompt_builder.question - DeepsetNvidiaTextEmbedder.text - DeepsetAnswerBuilder.query outputs: answers: DeepsetAnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents to extract images from with metadata containing file paths to image or PDF files. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `image_contents` | List[Optional[ImageContent]] | A list of `ImageContent` objects extracted from the documents, or `None` for documents that couldn't be processed. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `file_path_meta_field` | str | file_path | The metadata field in the Document that contains the file path to the image or PDF. | | `root_path` | Optional[str] | None | The root directory path where document files are located. If provided, file paths in document metadata will be resolved relative to this path. If None, file paths are treated as absolute paths. | | `detail` | Optional[Literal] | None | Optional detail level of the image (only supported by OpenAI). Can be "auto", "high", or "low". This will be passed to the created ImageContent objects. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents with metadata containing file paths to image or PDF files. | --- ## FileToFileContent Converts local files into `FileContent` objects that can be embedded into `ChatMessage` objects and passed to an LLM. `FileContent` objects contain the base64-encoded file data, MIME type, and filename. The component automatically detects the MIME type of each file. Empty files are skipped with a warning. ## Key Features - Converts files of any supported format to `FileContent` objects for direct LLM input. - Automatically detects MIME types. - Supports optional extra metadata for provider-specific information. - Skips empty files gracefully with a warning. ## Configuration 1. Drag the `FileToFileContent` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. This component has no init parameters to configure in Pipeline Builder. ## Connections `FileToFileContent` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `FileContent` objects. It typically connects with: - `FileTypeRouter`: receives files routed by MIME type. - `ChatPromptBuilder`: sends `FileContent` objects for inclusion in chat messages to an LLM. ## Source Code To check this component's source code, open [`file_to_file_content.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/file_to_file_content.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml FileToFileContent: type: haystack.components.converters.file_to_file_content.FileToFileContent init_parameters: {} ``` ### Using the Component in a Pipeline In this pipeline, `FileToFileContent` converts files and passes them to a chat generator through a `ChatPromptBuilder`: ```yaml # haystack-pipeline components: FileToFileContent: type: haystack.components.converters.file_to_file_content.FileToFileContent init_parameters: {} ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "Analyze the following files and answer questions about them." _role: system - _content: - text: "{{ query }}" _role: user required_variables: variables: ChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false connections: - sender: FileToFileContent.file_contents receiver: ChatPromptBuilder.file_contents - sender: ChatPromptBuilder.prompt receiver: ChatGenerator.messages inputs: files: - FileToFileContent.sources query: - ChatPromptBuilder.query outputs: replies: ChatGenerator.replies max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `extra` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional extra information to attach to the `FileContent` objects. Can be used to store provider-specific information. Values should be JSON serializable. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the extra of all produced `FileContent` objects. If it's a list, its length must match the number of sources as they're zipped together. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `file_contents` | List[FileContent] | A list of `FileContent` objects created from the input files. | ### Init Parameters This component has no init parameters. ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `extra` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional extra information to attach to the `FileContent` objects. Can be used to store provider-specific information. Values should be JSON serializable. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the extra of all produced `FileContent` objects. If it's a list, its length must match the number of sources as they're zipped together. | --- ## HTMLToDocument Convert HTML files to documents your pipeline can query, with customizable text extraction options. `HTMLToDocument` uses the Trafilatura library to extract text from HTML files. You can use it in indexes or in query pipelines after `LinkContentFetcher` to index content from websites. ## Key Features - Extracts text from HTML using the Trafilatura library. - Customizable extraction via keyword arguments (output format, language filtering, table and link inclusion). - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `HTMLToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Configure **Extraction Kwargs** to customize how content is extracted from HTML files. For example, set `output_format` to `markdown` or `txt`, enable `include_tables`, or set `target_language` to filter by language. For the full list of options, see the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `HTMLToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives HTML files routed by MIME type. - `LinkContentFetcher`: receives fetched web page content as `ByteStream` objects. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`html.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/html.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown include_tables: true include_links: true ``` ### Using the Component in an Index In this index, `HTMLToDocument` receives HTML files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/markdown - text/html - text/csv markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: # Defines how the components are connected - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: document_embedder.documents receiver: writer.documents - sender: csv_converter.documents receiver: joiner.documents - sender: splitter.documents receiver: document_embedder.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of HTML file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists are zipped. If `sources` contains ByteStream objects, their `meta` is added to the output Documents. | | `extraction_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments to customize the extraction process. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `extraction_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize the extraction process. These are passed to the underlying Trafilatura `extract` function. For the full list of available arguments, see the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). | | `store_full_path` | bool | False | If True, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of HTML file paths or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | | `extraction_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments to customize the extraction process. | --- ## ImageFileToDocument Convert references to image files into empty Document objects with associated metadata. `ImageFileToDocument` doesn't extract any content from the image files. Instead, it creates `Document` objects with `None` as their content and attaches metadata such as the file path and any user-provided values. Use it in pipelines where image file paths must be wrapped in `Document` objects so that downstream components can process them. ## Key Features - Wraps image file paths in `Document` objects for downstream processing. - Supports file paths (str or Path) and `ByteStream` objects as input. - Optional metadata attachment to resulting documents. - Works with image embedding components like `SentenceTransformersDocumentEmbedder` (with an image-capable model) and content extraction components like `LLMDocumentContentExtractor`. ## Configuration 1. Drag the `ImageFileToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `ImageFileToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects with empty content and file path metadata. It typically connects with: - `FilesInput`: receives image file paths. - `SentenceTransformersDocumentEmbedder` (with a CLIP model) or `LLMDocumentContentExtractor`: sends document references for embedding or content extraction. - `DocumentWriter`: sends documents for storage after embedding. ## Source Code To check this component's source code, open [`file_to_document.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/image/file_to_document.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml image_file_to_document: type: haystack.components.converters.image.file_to_document.ImageFileToDocument init_parameters: store_full_path: true ``` ### Using the Component in an Index Here's an example of `ImageFileToDocument` used in an index. It converts image file paths into Document objects that can then be embedded and stored for later retrieval: ```yaml # haystack-pipeline components: image_file_to_document: type: haystack.components.converters.image.file_to_document.ImageFileToDocument init_parameters: store_full_path: true SentenceTransformersImageDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: clip-ViT-B-32 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false meta_fields_to_embed: embedding_separator: "\\n" DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: image-index max_chunk_bytes: 104857600 embedding_dim: 512 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: image_file_to_document.documents receiver: SentenceTransformersImageDocumentEmbedder.documents - sender: SentenceTransformersImageDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - image_file_to_document.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of image file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Document objects with empty content and associated metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `store_full_path` | bool | False | If `True`, stores the full path of the file in the metadata of the document. If `False`, stores only the file name. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of image file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output documents. | --- ## ImageFileToImageContent Convert image files to `ImageContent` objects for multimodal AI processing, including tasks like image captioning or visual question answering. `ImageFileToImageContent` reads image files from various sources and creates `ImageContent` objects containing base64-encoded image data and associated metadata. ## Key Features - Converts image files to base64-encoded `ImageContent` objects ready for multimodal AI models. - Supports various image formats. - Optional image resizing to reduce file size and processing time while maintaining aspect ratio. - Configurable detail level for optimization with OpenAI vision models. ## Configuration 1. Drag the `ImageFileToImageContent` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Detail** level for images (`auto`, `high`, or `low`). This is passed to the created `ImageContent` objects and is only supported by OpenAI. - Set the **Size** to resize images to the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. ## Connections `ImageFileToImageContent` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `ImageContent` objects. It typically connects with: - `FilesInput`: receives image file paths. - `ChatPromptBuilder`: sends `ImageContent` objects to include in multimodal prompts for vision-capable models. ## Source Code To check this component's source code, open [`file_to_image.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/image/file_to_image.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml ImageFileToImageContent: type: haystack.components.converters.image.ImageFileToImageContent init_parameters: detail: auto ``` ### Using the Component in a Pipeline This is an example query pipeline that uses `ImageFileToImageContent` to convert uploaded images to `ImageContent` objects for multimodal processing. The images are sent to a `ChatPromptBuilder` along with a user question, and then processed by a vision-enabled chat generator: ```yaml # haystack-pipeline components: ImageFileToImageContent: type: haystack.components.converters.image.ImageFileToImageContent init_parameters: detail: auto size: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are an AI assistant that can analyze images and answer questions about them." _role: system - _content: - text: "{% for image in images %}{{ image }}{% endfor %}\n\nQuestion: {{ query }}" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: streaming_callback: tools: connections: - sender: ImageFileToImageContent.image_contents receiver: ChatPromptBuilder.images - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies inputs: query: - ChatPromptBuilder.query - answer_builder.query files: - ImageFileToImageContent.sources outputs: answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of image file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the `ImageContent` objects. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced `ImageContent` objects. If it's a list, its length must match the number of sources as they're zipped together. For `ByteStream` objects, their `meta` is added to the output `ImageContent` objects. | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). This is passed to the created `ImageContent` objects. If not provided, the detail level is the one set in the constructor. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. If not provided, the size value is the one set in the constructor. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `image_contents` | List[ImageContent] | A list of `ImageContent` objects created from the input image files. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). Possible values: "auto", "high", or "low". This is passed to the created `ImageContent` objects. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of image file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the ImageContent objects. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced ImageContent objects. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output ImageContent objects. | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). This will be passed to the created ImageContent objects. If not provided, the detail level will be the one set in the constructor. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. If not provided, the size value will be the one set in the constructor. | --- ## JSONConverter Convert JSON files into documents your pipelines can query. ## Key Features - Filters JSON content using `jq` filter syntax to extract specific fields. - Configurable content key to select which JSON field becomes the document content. - Optional extraction of additional metadata fields from the JSON source. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `JSONConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **JQ Schema** to filter the JSON source and extract only specific parts. For information on the filter syntax, see the [jq documentation](https://jqlang.github.io/jq/). If not specified, the whole JSON file is used. - Set the **Content Key** to specify which key from the extracted object becomes the document's content. You must set either `jq_schema`, `content_key`, or both. - Set **Extra Meta Fields** to specify additional keys to extract as document metadata from the filtered JSON. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `JSONConverter` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives JSON files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`json.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/json.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml JSONConverter: type: haystack.components.converters.json.JSONConverter init_parameters: store_full_path: false ``` ### Using the Component in an Index In this index, `JSONConverter` receives JSON files from `FileTypeRouter` and sends them to `DocumentJoiner` that combines documents from different converters. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/text - text/markdown - application/json additional_mimetypes: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: aga-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: JSONConverter: type: haystack.components.converters.json.JSONConverter init_parameters: jq_schema: content_key: extra_meta_fields: store_full_path: false connections: - sender: FileTypeRouter.text/text receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents - sender: FileTypeRouter.application/json receiver: JSONConverter.sources - sender: JSONConverter.documents receiver: DocumentJoiner.documents max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, the length of the list must match the number of sources. If `sources` contain ByteStream objects, their `meta` will be added to the output documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of created documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `jq_schema` | Optional[str] | None | Optional jq filter string to extract content. If not specified, the whole JSON object will be used to extract information. | | `content_key` | Optional[str] | None | Optional key to extract document content. If `jq_schema` is specified, the `content_key` will be extracted from that object. | | `extra_meta_fields` | Optional[Union[Set[str], Literal['*']]] | None | An optional set of meta keys to extract from the content. If `jq_schema` is specified, all keys will be extracted from that object. | | `store_full_path` | bool | False | If True, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, the length of the list must match the number of sources. If `sources` contain ByteStream objects, their `meta` will be added to the output documents. | --- ## JsonParser Extract and parse JSON from text input, handling both plain JSON and Markdown code blocks. This is useful for processing language model outputs that return JSON data wrapped in Markdown formatting. `JsonParser` is useful when processing language model outputs that return JSON data, as models often wrap JSON in Markdown formatting. ## Key Features - Parses plain JSON strings. - Handles JSON wrapped in Markdown code blocks (` ```json ... ``` `). - Handles JSON wrapped in generic code blocks (` ``` ... ``` `). - Configurable regex pattern for code block extraction. ## Configuration 1. Drag the `JsonParser` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Code Block Pattern** if you need a custom regex to extract JSON from code blocks. The default pattern handles standard Markdown JSON blocks. ## Connections `JsonParser` accepts a text string through its `text` input. It outputs the parsed JSON as a dictionary. It typically connects with: - `OpenAIChatGenerator` or other generators (usually through an `OutputAdapter`): receives text containing JSON output from an LLM. - `ConditionalRouter`: sends the parsed JSON dictionary for conditional routing logic. ## Usage Examples ### Basic Configuration ```yaml JsonParser: type: deepset_cloud_custom_nodes.parsers.json_parser.JsonParser init_parameters: {} ``` This is an example of `JsonParser` that receives text containing JSON from a generator and parses it. There is an `OutputAdapter` between the generator and `JsonParser` to align the input and output types of these two components: ```yaml # haystack-pipeline components: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ last_message }}" output_type: str custom_filters: unsafe: false JsonParser: type: deepset_cloud_custom_nodes.parsers.json_parser.JsonParser init_parameters: code_block_pattern: '```(?:json)?\n(.*?)\n```' ConditionalRouter: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: routes: - condition: '{{decision.mode == "PASSAGE"}}' output: '{{history}}' output_name: followup output_type: typing.List[haystack.dataclasses.ChatMessage] - condition: '{{decision.mode == "FRAGE" and decision.complexity in ["simple", "medium"]}}' output: '{{decision.query}}' output_name: search output_type: str - condition: '{{decision.mode == "FRAGE" and decision.complexity not in ["simple", "medium"]}}' output: '{{decision.query}}' output_name: agent output_type: typing.List[haystack.dataclasses.ChatMessage] - condition: '{{True}}' output: '{{(history|last).text}}' output_name: search_last_history output_type: str custom_filters: {} unsafe: false validate_output_type: false optional_variables: LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: >- {% message role="system" %} \nDu bist ein exzellentes Labelling-Tool.\nDu bekommst einen Chatverlauf.\n\n**1. Label Bestimmung**\nFalls die letzte user Frage nach Informationen aus einer Datenbank sucht, gebe \"FRAGE\" aus.\nDies ist auch der Fall, wenn etwas erklärt werden soll oder eine Aufgabe gestellt wird, deren Lösung den Abruf von neuen Informationen erfordert (z.B. Vergleiche, Tabellen, Analysen erstellen).\n**WICHTIG:** Auch reine Sachverhaltsschilderungen (z.B. juristische Fälle) ohne explizite Frage fallen unter das Label \"FRAGE\", da sie implizit nach einer rechtlichen Einordnung oder ähnlichen Fällen suchen.\n\nFalls die letzte user Frage Instruktionen sind zum Arbeiten mit einer bereits im Chatverlauf vorhandenen oder vom User explizit bereitgestellten Passage, gebe \"PASSAGE\" aus. Dies gilt nur, wenn keine neuen Informationen aus einer Datenbank abgerufen werden müssen.\nFalls der Chatverlauf nur eine user Message enthält, kann nicht das Label \"PASSAGE\" ausgegeben werden.\nBeispielfragen, welche sich auf die Passage beziehen, sind: 'schreibe davon eine zusammenfassung', 'in stichpunkten' oder 'formuliere als email um'.\n\n**2. Output für \"PASSAGE\"**\nFür das Label \"PASSAGE\" gibst du NICHTS zusätzlich aus.\nFormat: { \"label\": \"PASSAGE\" }\n\n**3. Output für \"FRAGE\"**\nFür das Label \"FRAGE\" gibst du zusätzlich \"query\" und \"complexity\" aus.\n\n**A) Query-Generierung:**\nDie \"query\" muss in natürlicher Sprache sein, da sie von einer keyword und einer semantic search hybrid verarbeitet wird. Sei daher möglichst explizit mit den Keywords.\n\n**Spezialfall Sachverhalt:** Wenn der User-Input eine reine Sachverhaltsschilderung (Fakten, Fallbeispiel) ohne explizite Frage ist, generiere als \"query\" eine prägnante **Fallbeschreibung**, die die wesentlichen Fakten und juristischen Probleme zusammenfasst (z.B. \"Fallbeschreibung: Schenkung unter Auflage, nachträglicher Diebstahl durch Beschenkte und Haftung für Drittschaden\"). Formuliere in diesem Fall KEINE hypothetischen Fragen.\n\nWenn nach X auch nach Y gefragt wird, frage in der \"query\" nur nach Y und wiederhole nicht noch einmal X.\nAbkürzungen wie \"ArbVG\", \"BVwG\" oder \"Abs\", sowie alle Paragraphen bleiben bestehen und dürfen in der \"query\" nicht umformuliert werden.\nWenn die Frage keinen Kontext aus der Chat Historie benötigt, gebe sie unbearbeitet in \"query\" aus.\n\n**B) Komplexitätsbestimmung (Complexity Analysis):**\nBestimme die Komplexität des Retrievals (\"complexity\") basierend auf der Schwierigkeit der Anfrage:\n- **simple**: 1-2 Aspekte/Anspruchsgrundlagen, 1 Themengebiet, klare Faktenabfrage oder Definition, Standard-Recherche.\n- **medium**: 2-4 Aspekte, 2-3 Themengebiete, Vergleiche zwischen zwei Entitäten, Listen, abgrenzbare Themen.\n- **high**: 5-7 Aspekte, 3-4 Themengebiete mit Wechselwirkungen, Synthese aus mehreren Quellen nötig, Abhängigkeiten (Wenn X, dann Y).\n- **very_high**: ≥8 Aspekte ODER ≥3-stufige Verschachtelungen ODER systematische Widersprüche ODER sehr abstrakte Analyseanforderungen.\n\nFormat für FRAGE: { \"label\": \"FRAGE\", \"query\": \"...\", \"complexity\": \"...\" }\n\n\n\n\n{{ message.text }}\n\n\n\n\n{ \"label\": \"\n {% endmessage %} user_prompt: |- {% message role="user" %} {{ query }} {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: OutputAdapter.output receiver: JsonParser.text - sender: JsonParser.parsed_json receiver: ConditionalRouter.decision - sender: LLM.last_message receiver: OutputAdapter.last_message max_runs_per_component: 100 metadata: {} inputs: messages: - ConditionalRouter.history - LLM.message query: - LLM.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | Text containing JSON to parse. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `parsed_json` | Dict[str, Any] | The parsed JSON object. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `code_block_pattern` | str | "```(?:json)?\\n(.*?)\\n```" | Regular expression pattern to extract JSON from markdown code blocks. The pattern should include a capture group for the JSON content. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | Text containing JSON to parse. Can be plain JSON or JSON wrapped in markdown code blocks. | --- ## LinkContentFetcher Fetch and extract content from URLs. The component supports various content types, retries on failures, and automatic user-agent rotation for failed web requests. `LinkContentFetcher` supports various content types, retries on failures, and automatic user-agent rotation for failed web requests. Use it as the data-fetching step in pipelines that index or process web content. ## Key Features - Fetches content from a list of URLs and returns it as `ByteStream` objects. - Configurable retry attempts and timeout for resilient fetching. - Automatic user-agent rotation to handle sites that block default agents. - Optional HTTP/2 support. ## Configuration 1. Drag the `LinkContentFetcher` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Retry Attempts** to specify how many times to retry fetching a URL on failure. The default is two. - Set **Timeout** (in seconds) for each request. The default is three seconds. - Set **Raise on Failure** to control whether to raise an exception if fetching a single URL fails. - Set **User Agents** to provide a custom list of user agent strings for rotation. - Enable **HTTP/2** support if required (requires the `h2` package). - Set **Client Kwargs** for custom `httpx` client configuration. ## Connections `LinkContentFetcher` accepts a list of URL strings through its `urls` input. It outputs a list of `ByteStream` objects. It typically connects with: - Web search components like `SerperDevWebSearch`: receives URLs from search results. - Converters like `HTMLToDocument` or `MarkdownToDocument`: sends fetched `ByteStream` content for conversion to documents. ## Source Code To check this component's source code, open [`link_content.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/fetchers/link_content.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml fetcher: type: haystack.components.fetchers.link_content.LinkContentFetcher init_parameters: raise_on_failure: false retry_attempts: 2 timeout: 3 user_agents: - haystack/LinkContentFetcher/2.11.1 ``` ### Using the Component in an Index This index uses `LinkContentFetcher` to fetch web content and convert it to documents: ```yaml # haystack-pipeline components: builder: init_parameters: required_variables: "*" template: |- {% for doc in docs %} {% if doc.content and doc.meta.url|length > 0 %} {{ doc.content|truncate(25000) }} {% endif %} {% endfor %} variables: type: haystack.components.builders.prompt_builder.PromptBuilder converter: init_parameters: extraction_kwargs: {} store_full_path: false type: haystack.components.converters.html.HTMLToDocument fetcher: init_parameters: raise_on_failure: false retry_attempts: 2 timeout: 3 user_agents: - haystack/LinkContentFetcher/2.11.1 type: haystack.components.fetchers.link_content.LinkContentFetcher search: init_parameters: api_key: env_vars: - SERPERDEV_API_KEY strict: false type: env_var search_params: {} top_k: 10 type: haystack.components.websearch.serper_dev.SerperDevWebSearch AnthropicGenerator: type: haystack_integrations.components.generators.anthropic.generator.AnthropicGenerator init_parameters: api_key: type: env_var env_vars: - ANTHROPIC_API_KEY strict: false model: claude-sonnet-4-20250514 streaming_callback: system_prompt: generation_kwargs: timeout: max_retries: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true connections: - receiver: fetcher.urls sender: search.links - receiver: converter.sources sender: fetcher.streams - receiver: builder.docs sender: converter.documents - sender: builder.prompt receiver: AnthropicGenerator.prompt - sender: AnthropicGenerator.replies receiver: AnswerBuilder.replies max_runs_per_component: 100 metadata: {} inputs: query: - search.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `urls` | List[str] | A list of URLs to fetch content from. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `streams` | List[ByteStream] | `ByteStream` objects representing the extracted content. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `raise_on_failure` | bool | True | If `True`, raises an exception if it fails to fetch a single URL. For multiple URLs, it logs errors and returns the content it successfully fetched. | | `user_agents` | Optional[List[str]] | None | [User agents](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) for fetching content. If `None`, a default user agent is used. | | `retry_attempts` | int | 2 | The number of times to retry fetching the URL's content. | | `timeout` | int | 3 | Timeout in seconds for the request. | | `http2` | bool | False | Whether to enable HTTP/2 support for requests. Requires the `h2` package to be installed (via `pip install httpx[http2]`). | | `client_kwargs` | Optional[Dict] | None | Additional keyword arguments to pass to the httpx client. If `None`, default values are used. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `urls` | List[str] | A list of URLs to fetch content from. | --- ## MSGToDocument Convert Microsoft Outlook MSG files into documents your pipelines can query. The component extracts email metadata and body content, and returns file attachments as separate ByteStream objects. `MSGToDocument` extracts email metadata (such as sender, recipients, CC, BCC, subject) and body content from MSG files and converts them into structured documents. It also extracts file attachments as `ByteStream` objects. ## Key Features - Extracts email metadata (sender, recipients, CC, BCC, subject) and body content. - Outputs attachments as separate `ByteStream` objects for further processing. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `MSGToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `MSGToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs converted `Document` objects and any file attachments as `ByteStream` objects. It typically connects with: - `FileTypeRouter`: receives MSG files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`msg.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/msg.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MSGToDocument: type: haystack.components.converters.msg.MSGToDocument init_parameters: store_full_path: false ``` ### Using the Component in an Index This index converts MSG files to documents and sends them to `DocumentJoiner` that combines them with documents coming from other converters. The joined documents are then sent to `DocumentSplitter`. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/text - text/markdown - application/vnd.ms-outlook additional_mimetypes: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: aga-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: MSGToDocument: type: haystack.components.converters.msg.MSGToDocument init_parameters: store_full_path: false connections: - sender: FileTypeRouter.text/text receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents - sender: FileTypeRouter.application/vnd.ms-outlook receiver: MSGToDocument.sources - sender: MSGToDocument.documents receiver: DocumentJoiner.documents max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | | `attachments` | List[ByteStream] | Created ByteStream objects from file attachments. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `store_full_path` | bool | False | If `True`, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | --- ## MarkdownToDocument Convert Markdown files into text documents your pipeline can query. Use this component in indexes to write Markdown file contents into a document store. ## Key Features - Converts Markdown files to plain-text documents for indexing and search. - Optional table-to-single-line conversion to simplify table content. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `MarkdownToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Enable **Table to Single Line** if you want table contents converted to a single line. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. - Toggle **Progress Bar** to show or hide a progress bar during conversion. ## Connections `MarkdownToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives Markdown files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`markdown.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/markdown.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false ``` ### Using the Component in an Index In this index, `MarkdownToDocument` receives Markdown files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/text - text/markdown - application/json additional_mimetypes: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: aga-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: JSONConverter: type: haystack.components.converters.json.JSONConverter init_parameters: jq_schema: content_key: extra_meta_fields: store_full_path: false connections: - sender: FileTypeRouter.text/text receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents - sender: FileTypeRouter.application/json receiver: JSONConverter.sources - sender: JSONConverter.documents receiver: DocumentJoiner.documents max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `table_to_single_line` | bool | False | If `True` converts table contents into a single line. | | `progress_bar` | bool | True | If `True` shows a progress bar when running. | | `store_full_path` | bool | False | If `True`, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | --- ## MultiFileConverter Convert multiple file types to documents in a single operation. The component automatically detects each file's type and applies the appropriate converter. `MultiFileConverter` is a SuperComponent that combines `FileTypeRouter`, nine converters, and `DocumentJoiner` into a single component. It automatically detects file types and applies the appropriate converter for each file, so you don't need to manually connect individual converter components. ## Key Features - Automatically detects file types and routes each file to the appropriate converter. - Supports nine file types: CSV, DOCX, HTML, JSON, Markdown, plain text, PDF, PPTX, and XLSX. - Returns a list of failed files separately so you can handle conversion errors. - Simplifies pipeline design by replacing multiple converter components with one. ## Configuration 1. Drag the `MultiFileConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Encoding** for text-based files. The default is UTF-8. - Set the **JSON Content Key** to specify which key to use as document content when converting JSON files. The default is `content`. ## Connections `MultiFileConverter` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of successfully converted `Document` objects and a list of file paths that failed to convert. It typically connects with: - `FilesInput`: receives files to convert. - `DocumentSplitter` or document embedding components: sends converted documents for further processing. ## Source Code To check this component's source code, open [`multi_file_converter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/multi_file_converter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MultiFileConverter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 json_content_key: content ``` ### Using the Component in an Index In this index, `MultiFileConverter` receives files, converts them, and then sends them to `DocumentSplitter`. ```yaml # haystack-pipeline components: MultiFileConverter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 json_content_key: content DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true skip_empty_documents: true DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' batch_size: 32 meta_fields_to_embed: embedding_separator: \n truncate: normalize_embeddings: true timeout: backend_kwargs: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: MultiFileConverter.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DeepsetNvidiaDocumentEmbedder.documents - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - MultiFileConverter.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths or byte streams to convert. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of converted documents. Only included if at least one file is successfully converted. | | `failed` | List[str] | A list of files that failed to convert. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `encoding` | str | utf-8 | The encoding to use when reading text files. | | `json_content_key` | str | content | The key to extract content from JSON files. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths or byte streams to convert. | --- ## PDFMinerToDocument Convert PDF files to documents using PDFMiner's extraction parameters. Use this component when you need fine-grained control over layout analysis and text extraction from PDFs. `PDFMinerToDocument` uses `pdfminer`-compatible converters to extract text from PDF files. It exposes detailed layout analysis parameters for fine-tuned control over text extraction. For details, see the [PDFMiner documentation](https://pdfminersix.readthedocs.io/en/latest/). ## Key Features - Fine-grained control over PDF text extraction with layout analysis parameters. - Configurable margins for character, word, and line grouping. - Optional vertical text detection. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `PDFMinerToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - This component works with default settings for most PDFs. Adjust the settings below if you need to tune extraction for specific PDF layouts. - Set **Line Overlap** to adjust how characters are grouped onto the same line (default: 0.5). - Set **Char Margin** to control the distance threshold for grouping characters on the same line (default: 2). - Set **Word Margin** to control when an intermediate space is inserted between characters (default: 0.1). - Set **Line Margin** to control the distance threshold for grouping lines into paragraphs (default: 0.5). - Set **Boxes Flow** to control whether horizontal or vertical position takes precedence when ordering text boxes (default: 0.5, range: -1.0 to 1.0). - Enable **Detect Vertical** to include vertical text in layout analysis. - Enable **All Texts** to perform layout analysis on text in figures. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `PDFMinerToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives PDF files routed by MIME type. - `DocumentSplitter` or other preprocessors: sends converted documents for further processing. ## Source Code To check this component's source code, open [`pdfminer.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/pdfminer.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false ``` ### Using the Component in an Index This is a simple index you can use if you only have PDF files to index. ```yaml # haystack-pipeline components: DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true skip_empty_documents: true DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' batch_size: 32 meta_fields_to_embed: embedding_separator: \n truncate: normalize_embeddings: true timeout: backend_kwargs: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false connections: - sender: DocumentSplitter.documents receiver: DeepsetNvidiaDocumentEmbedder.documents - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents - sender: PDFMinerToDocument.documents receiver: DocumentSplitter.documents max_runs_per_component: 100 metadata: {} inputs: files: - PDFMinerToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of PDF file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `line_overlap` | float | 0.5 | Determines whether two characters are considered to be on the same line based on the amount of overlap between them. The overlap is calculated relative to the minimum height of both characters. | | `char_margin` | float | 2 | Determines whether two characters are part of the same line based on the distance between them. If the distance is less than the margin specified, the characters are considered to be on the same line. The margin is calculated relative to the width of the character. | | `word_margin` | float | 0.1 | Determines whether two characters on the same line are part of the same word based on the distance between them. If the distance is greater than the margin specified, an intermediate space will be added between them to make the text more readable. The margin is calculated relative to the width of the character. | | `line_margin` | float | 0.5 | Determines whether two lines are part of the same paragraph based on the distance between them. If the distance is less than the margin specified, the lines are considered to be part of the same paragraph. The margin is calculated relative to the height of a line. | | `boxes_flow` | Optional[float] | 0.5 | Determines the importance of horizontal and vertical position when determining the order of text boxes. A value between -1.0 and +1.0 can be set, with -1.0 indicating that only horizontal position matters and +1.0 indicating that only vertical position matters. Setting the value to 'None' disables advanced layout analysis, and text boxes are ordered based on the position of their bottom left corner. | | `detect_vertical` | bool | True | Determines whether vertical text should be considered during layout analysis. | | `all_texts` | bool | False | If layout analysis should be performed on text in figures. | | `store_full_path` | bool | False | If `True`, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of PDF file paths or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | --- ## PDFToImageContent Convert PDF files to `ImageContent` objects for multimodal AI processing. Each converted page becomes a separate `ImageContent` object containing base64-encoded image data and associated metadata. `PDFToImageContent` reads PDF files and converts specified pages into images, creating `ImageContent` objects containing base64-encoded image data and metadata. Each converted page becomes a separate `ImageContent` object with metadata indicating the source file and page number. ## Key Features - Converts PDF pages to base64-encoded `ImageContent` objects for multimodal AI models. - Supports specific page selection and page ranges. - Optional image resizing to reduce file size while maintaining aspect ratio. - Configurable detail level for optimization with OpenAI vision models. ## Configuration 1. Drag the `PDFToImageContent` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Page Range** to specify which pages to convert. Accepts page numbers and ranges, for example `['1-3', '5', '8']`. If not set, all pages are converted. - Set the **Detail** level for images (`auto`, `high`, or `low`). This is passed to the created `ImageContent` objects and is only supported by OpenAI. - Set the **Size** to resize images to the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. ## Connections `PDFToImageContent` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `ImageContent` objects, one per converted page. It typically connects with: - `FilesInput` or `FileTypeRouter`: receives PDF files. - `ChatPromptBuilder`: sends extracted page images to include in multimodal prompts. ## Source Code To check this component's source code, open [`pdf_to_image.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/image/pdf_to_image.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml PDFToImageContent: type: haystack.components.converters.image.PDFToImageContent init_parameters: detail: auto page_range: - 1-3 ``` ### Using the Component in a Pipeline This example shows a query pipeline that uses `PDFToImageContent` to convert uploaded PDF pages to images for multimodal AI processing. The pipeline extracts specified pages from PDF documents, converts them to `ImageContent` objects, and sends them to a vision-enabled chat model for analysis. ```yaml # haystack-pipeline components: PDFToImageContent: type: haystack.components.converters.image.PDFToImageContent init_parameters: detail: auto size: page_range: - "1-3" ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: >- You are an AI assistant that analyzes PDF documents. Examine the provided PDF pages and answer questions about their content, layout, text, images, and any other visible elements. - role: user content: "{{ question }}" images: "{{ images }}" required_variables: - question - images OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o generation_kwargs: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0].text }}" output_type: str DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: connections: - sender: PDFToImageContent.image_contents receiver: ChatPromptBuilder.images - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: DeepsetAnswerBuilder.replies inputs: query: - ChatPromptBuilder.question files: - PDFToImageContent.sources outputs: answers: DeepsetAnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of PDF file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the `ImageContent` objects. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced `ImageContent` objects. If it's a list, its length must match the number of sources as they're zipped together. For `ByteStream` objects, their `meta` is added to the output `ImageContent` objects. | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). This is passed to the created `ImageContent` objects. If not provided, the detail level is the one set in the constructor. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. If not provided, the size value is the one set in the constructor. | | `page_range` | Optional[List[Union[str, int]]] | None | List of page numbers and page ranges to convert to images. If not provided, the page range is the one set in the pipeline configuration. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `image_contents` | List[ImageContent] | A list of `ImageContent` objects created from the PDF pages. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). Possible values: "auto", "high", or "low". This is passed to the created `ImageContent` objects. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. | | `page_range` | Optional[List[Union[str, int]]] | None | List of page numbers and page ranges to convert to images. Page numbers start at 1. If `None`, all pages in the PDF are converted. Also accepts printable range strings, for example: ['1-3', '5', '8', '10-12']. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of PDF file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the `ImageContent` objects. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced `ImageContent` objects. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output `ImageContent` objects. | | `detail` | Optional[Literal["auto", "high", "low"]] | None | Optional detail level of the image (only supported by OpenAI). This is passed to the created `ImageContent` objects. If not provided, the detail level is the one set in the constructor. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. If not provided, the size value is the one set in the constructor. | | `page_range` | Optional[List[Union[str, int]]] | None | List of page numbers and page ranges to convert to images. Page numbers start at 1. If `None`, all pages in the PDF are converted. Pages outside the valid range are skipped with a warning. Also accepts printable range strings, for example: ['1-3', '5', '8', '10-12']. | --- ## PPTXToDocument Convert PPTX files to documents your pipeline can query. ## Key Features - Converts PowerPoint presentation files to text documents for indexing. - Configurable link format output: plain text, Markdown, or no links. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `PPTXToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Link Format** to control how hyperlinks appear in the extracted text: `none` (default, text only), `markdown` (for `[text](url)`), or `plain` (for `text (url)`). - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `PPTXToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives PPTX files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`pptx.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/pptx.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml PPTXToDocument: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: store_full_path: false ``` ### Using the Component in an Index In this index, `PPTXToDocument` receives PPTX files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - application/vnd.openxmlformats-officedocument.presentationml.presentation additional_mimetypes: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false PyPDFToDocument: type: haystack.components.converters.pypdf.PyPDFToDocument init_parameters: store_full_path: false PPTXToDocument: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: presentation-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PyPDFToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: PPTXToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: PyPDFToDocument.documents receiver: DocumentJoiner.documents - sender: PPTXToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `store_full_path` | bool | False | If `True`, the full path of the file is stored in the metadata of the document. If `False`, only the file name is stored. | | `link_format` | Literal['markdown', 'plain', 'none'] | none | The format for link output. Options: `"markdown"` for `[text](url)`, `"plain"` for `text (url)`, `"none"` to extract only the text and ignore link addresses. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | --- ## PyPDFToDocument Convert PDF files to documents your pipeline can query. This component uses the PyPDF library to extract text from PDFs and supports both plain and layout-aware extraction modes. `PyPDFToDocument` uses the PyPDF library to extract text from PDF files. It supports two extraction modes: plain (default) and layout (experimental, adheres to the rendered layout of the PDF). ## Key Features - Two extraction modes: plain text and layout-aware (experimental). - Configurable orientation support for rotated pages in plain mode. - Fine-grained layout mode parameters for vertical spacing and font handling. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `PyPDFToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Extraction Mode** to choose between `plain` (default) or `layout` (experimental layout-aware extraction). - **Plain mode**: set `plain_mode_orientations` to specify which page orientations to look for, and `plain_mode_space_width` to control default space width. - **Layout mode**: set `layout_mode_space_vertically`, `layout_mode_scale_weight`, `layout_mode_strip_rotated`, and `layout_mode_font_height_weight` to tune layout extraction. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `PyPDFToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives PDF files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`pypdf.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/pypdf.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml PyPDFToDocument: type: haystack.components.converters.pypdf.PyPDFToDocument init_parameters: extraction_mode: PyPDFExtractionMode.PLAIN plain_mode_orientations: - 0 - 90 - 180 - 270 plain_mode_space_width: 200.0 layout_mode_space_vertically: true layout_mode_scale_weight: 1.25 layout_mode_strip_rotated: true layout_mode_font_height_weight: 1.0 store_full_path: false ``` ### Using the Component in an Index In this index, `PyPDFToDocument` receives PDF files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false PyPDFToDocument: type: haystack.components.converters.pypdf.PyPDFToDocument init_parameters: extraction_mode: PyPDFExtractionMode.PLAIN plain_mode_orientations: - 0 - 90 - 180 - 270 plain_mode_space_width: 200.0 layout_mode_space_vertically: true layout_mode_scale_weight: 1.25 layout_mode_strip_rotated: true layout_mode_font_height_weight: 1.0 store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: pdf-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PyPDFToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: PyPDFToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources, as they are zipped together. For ByteStream objects, their `meta` is added to the output documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `extraction_mode` | Union[str, PyPDFExtractionMode] | PyPDFExtractionMode.PLAIN | The mode to use for extracting text from a PDF. Layout mode is an experimental mode that adheres to the rendered layout of the PDF. | | `plain_mode_orientations` | tuple | (0, 90, 180, 270) | Tuple of orientations to look for when extracting text from a PDF in plain mode. Ignored if `extraction_mode` is `PyPDFExtractionMode.LAYOUT`. | | `plain_mode_space_width` | float | 200.0 | Forces default space width if not extracted from font. Ignored if `extraction_mode` is `PyPDFExtractionMode.LAYOUT`. | | `layout_mode_space_vertically` | bool | True | Whether to include blank lines inferred from y distance + font height. Ignored if `extraction_mode` is `PyPDFExtractionMode.PLAIN`. | | `layout_mode_scale_weight` | float | 1.25 | Multiplier for string length when calculating weighted average character width. Ignored if `extraction_mode` is `PyPDFExtractionMode.PLAIN`. | | `layout_mode_strip_rotated` | bool | True | Layout mode does not support rotated text. Set to `False` to include rotated text anyway. If rotated text is discovered, layout will be degraded and a warning will be logged. Ignored if `extraction_mode` is `PyPDFExtractionMode.PLAIN`. | | `layout_mode_font_height_weight` | float | 1.0 | Multiplier for font height when calculating blank line height. Ignored if `extraction_mode` is `PyPDFExtractionMode.PLAIN`. | | `store_full_path` | bool | False | If True, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources, as they are zipped together. For ByteStream objects, their `meta` is added to the output documents. | --- ## RemoteWhisperTranscriber Transcribe audio files using the OpenAI Whisper API. `RemoteWhisperTranscriber` uses OpenAI's Whisper API to transcribe audio files and return them as documents for storage in a document store. It's typically used in indexes. For supported audio formats, languages, and other parameters, see the [Whisper API documentation](https://platform.openai.com/docs/guides/speech-to-text). ## Key Features - Transcribes audio files to text documents using OpenAI's Whisper API. - Supports multiple audio formats (see Whisper API documentation for the full list). - Returns one document per audio file with the transcribed text as content. ## Configuration You need an OpenAI API key to use this component. Connect deepset AI Platform to OpenAI first: ::: 1. Drag the `RemoteWhisperTranscriber` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab, select the Whisper model to use. 4. Go to the **Advanced** tab to configure the API key, base URL, organization, timeout, max retries, and HTTP client settings. ## Connections `RemoteWhisperTranscriber` accepts a list of file paths or ByteStream objects (`sources`) containing audio files as input. It outputs a list of documents (`documents`), one per audio file, each containing the transcribed text. Typically, `RemoteWhisperTranscriber` receives audio files from a `FileClassifier` (or `FileTypeRouter`) that routes files by type. Its `documents` output connects to a `DocumentJoiner` to combine transcriptions with documents from other converters before splitting and indexing. 1. Drag the `RemoteWhisperTranscriber` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Model** to the Whisper model to use. Currently only `whisper-1` is supported. 4. Go to the **Advanced** tab to configure additional settings: - Set the **API Key** to your OpenAI API key (configured via the Integrations page). - Set **Organization** if you want to specify your OpenAI organization ID. - Set **API Base URL** to use a custom API endpoint. - Set **HTTP Client Kwargs** for custom `httpx` client configuration. - Set **kwargs** for additional model parameters such as `language`, `prompt`, `response_format`, or `temperature`. ## Source Code To check this component's source code, open [`whisper_remote.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/audio/whisper_remote.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `RemoteWhisperTranscriber` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects, one per audio file. It typically connects with: - `FileTypeRouter` or `FileClassifier`: receives audio files routed by MIME type. - `DocumentJoiner`: sends transcribed documents to join with documents from other converters. - `DocumentSplitter`: sends transcribed documents for splitting before further processing. ## Usage Examples ### Basic Configuration ```yaml RemoteWhisperTranscriber: type: haystack.components.audio.whisper_remote.RemoteWhisperTranscriber init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: whisper-1 ``` ### Using the Component in an Index This is an example of an index that can process PDF, text, and audio files. `FileClassifier` routes files by their type to the appropriate converter. The resulting documents are joined and sent to `DocumentSplitter`. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - video/mp4 text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE RemoteWhisperTranscriber: type: haystack.components.audio.whisper_remote.RemoteWhisperTranscriber init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: whisper-1 api_base_url: organization: http_client_kwargs: connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: document_embedder.documents receiver: writer.documents - sender: file_classifier.video/mp4 receiver: RemoteWhisperTranscriber.sources - sender: RemoteWhisperTranscriber.documents receiver: joiner.documents - sender: splitter.documents receiver: document_embedder.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths or `ByteStream` objects containing the audio files to transcribe. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents, one document for each file. The content of each document is the transcribed text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | OpenAI API key. Paste the API key on the Integrations page. | | `model` | str | whisper-1 | Name of the model to use. Currently accepts only `whisper-1`. | | `organization` | Optional[str] | None | Your OpenAI organization ID. See OpenAI's documentation on [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `api_base` | Any | | An optional URL to use as the API base. For details, see the OpenAI [documentation](https://platform.openai.com/docs/api-reference/audio). | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | | `kwargs` | Any | | Other optional parameters for the model. These are sent directly to the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/audio) for more details. Supported parameters include: `language` (ISO-639-1 format), `prompt`, `response_format` (only `json` is supported), and `temperature`. | | `api_base_url` | Optional[str] | None | An optional URL to use as the API base URL. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths or `ByteStream` objects containing the audio files to transcribe. | ## Related Information - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## TextFileToDocument Convert text files to documents your pipeline can query. Use this component in indexes to write text file contents into a document store. `TextFileToDocument` uses UTF-8 encoding by default, but you can set a custom encoding. You can also attach metadata to the resulting documents. ## Key Features - Converts plain text files to documents for indexing and search. - Configurable encoding with UTF-8 as default. - Optional metadata attachment to resulting documents. ## Configuration 1. Drag the `TextFileToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set the **Encoding** for the text files. The default is UTF-8. If encoding is specified in the metadata of a source `ByteStream`, it overrides this value. - Set **Store Full Path** to control whether the full file path or just the file name is stored in document metadata. ## Connections `TextFileToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives text files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. ## Source Code To check this component's source code, open [`txt.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/txt.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false ``` ### Using the Component in an Index In this index, `TextFileToDocument` receives text files from `FileTypeRouter` and sends them to `DocumentJoiner`. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - text/csv - application/json additional_mimetypes: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false JSONConverter: type: haystack.components.converters.json.JSONConverter init_parameters: jq_schema: content_key: extra_meta_fields: store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: text-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.text/csv receiver: CSVToDocument.sources - sender: FileTypeRouter.application/json receiver: JSONConverter.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: CSVToDocument.documents receiver: DocumentJoiner.documents - sender: JSONConverter.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents max_runs_per_component: 100 ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of text file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `encoding` | str | utf-8 | The encoding of the text files to convert. If the encoding is specified in the metadata of a source ByteStream, it overrides this value. | | `store_full_path` | bool | False | If `True`, the full path of the file is stored in the metadata of the document. If `False`, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of text file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the documents. This value can be a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced documents. If it's a list, its length must match the number of sources as they're zipped together. For ByteStream objects, their `meta` is added to the output documents. | --- ## XLSXToDocument Turn XLSX worksheets or rows into documents. This component uses pandas and openpyxl to read spreadsheets. ## Key Features - Two conversion modes: one document per worksheet (default) or one document per row. - Configurable content column for row mode — remaining columns become document metadata. - Sheet selection to limit conversion to specific worksheets. - Passes additional arguments to `pandas.read_excel` for advanced control. ## Configuration 1. Drag the `XLSXToDocument` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Set **Document Per** to `sheet` (default) to create one document per worksheet, or `row` to create one document per row. - If using row mode, set **Content Column** to specify which column becomes the document content. The default is `content`. - Optionally, set **Sheet Name** to limit conversion to specific sheets by name or index. If not set, all sheets are converted. - Set **kwargs** to pass additional arguments to `pandas.read_excel`, such as `engine`, `skiprows`, or `nrows`. ## Connections `XLSXToDocument` accepts a list of file paths or `ByteStream` objects through its `sources` input. It outputs a list of `Document` objects. It typically connects with: - `FileTypeRouter`: receives XLSX files routed by MIME type. - `DocumentJoiner`: sends converted documents to join with output from other converters before further processing. - `DocumentSplitter` or embedding components: sends documents for further processing. ## Usage Examples ### Basic Configuration ```yaml xlsx_converter: type: deepset_cloud_custom_nodes.converters.xlsx.XLSXToDocument init_parameters: document_per: row content_column: summary ``` ### Using the Component in an Index ```yaml # haystack-pipeline components: file_router: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: table_format: csv sheet_name: csv_converter: type: deepset_cloud_custom_nodes.converters.csv_rows_to_documents.DeepsetCSVRowsToDocumentsConverter init_parameters: {} joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: file_router.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_router.text/csv receiver: csv_converter.sources - sender: xlsx_converter.documents receiver: joiner.documents - sender: csv_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: DocumentWriter.documents inputs: files: - file_router.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | Paths or ByteStreams that point to XLSX files. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Metadata forwarded to every document or aligned per source. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents that contain CSV content or the selected row content plus merged metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_per` | Literal["sheet", "row"] | "sheet" | Create a document per worksheet or per row. | | `content_column` | str | "content" | Column that holds the content when `document_per` is set to `row`. | | `sheet_name` | Union[str, int, List[Union[str, int]], None] | None | Limit conversion to one sheet, several sheets, or leave `None` to read all sheets. | | `kwargs` | Dict[str, Any] | {} | Arguments forwarded to `pandas.read_excel`, such as `engine`, `skiprows`, or `nrows`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | XLSX file paths or ByteStreams. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Metadata applied to every generated document or aligned per source entry. | --- ## Convert Overview # Convert Group These components help you turn external inputs into content your pipeline can process. Use them to ingest sources such as files or web pages and convert them into a consistent representation that you can clean, split, embed, and store. This subgroup is a good fit for the start of indexing pipelines, where the main goal is to bring data into your system in a reliable way. It also helps you standardize inputs early, so the rest of your pipeline can focus on processing and retrieval rather than handling format differences. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## DocumentLanguageClassifier Classify documents by language and add the language to the document's metadata. ## Key Features - Detects the language of each document and stores it as a metadata field. - Supports a configurable list of target languages using ISO 639-1 codes. - Documents in languages not on the configured list are classified as unmatched. - Defaults to English (`en`) if no languages are specified. - Works well with `MetadataRouter` to route documents to different stores or processors by language. ## Configuration 1. Drag the `DocumentLanguageClassifier` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Enter the list of ISO 639-1 language codes you want to classify documents by, such as `en` for English or `de` for German. For a full list of supported languages, see the [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). ## Connections `DocumentLanguageClassifier` receives a list of documents as input, typically from a converter such as `TextFileToDocument`. It outputs a list of documents enriched with a `language` metadata field. Connect its output to `MetadataRouter` to route documents to different downstream components or document stores based on the detected language. You can also connect it to any component that accepts documents as input. ## Source Code To check this component's source code, open [`document_language_classifier.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/classifiers/document_language_classifier.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentLanguageClassifier: type: haystack.components.classifiers.document_language_classifier.DocumentLanguageClassifier init_parameters: {} ``` ### Using the Component in an Index In this index, `DocumentLanguageClassifier` sends classified documents to `MetadataRouter`. `MetadataRouter` then routes English documents to a different document store than the German documents. ```yaml # haystack-pipeline components: DocumentLanguageClassifier: type: haystack.components.classifiers.document_language_classifier.DocumentLanguageClassifier init_parameters: languages: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: english: operator: OR conditions: - field: language operator: == value: en german: operator: OR conditions: - field: language operator: == value: de DocumentWriter_English: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: DocumentWriter_German: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: bm25_tokenization_regex: (?u)\b\w\w+\b bm25_algorithm: BM25L bm25_parameters: embedding_similarity_function: dot_product index: '' async_executor: connections: # Defines how the components are connected - sender: TextFileToDocument.documents receiver: DocumentLanguageClassifier.documents - sender: DocumentLanguageClassifier.documents receiver: MetadataRouter.documents - sender: MetadataRouter.english receiver: DocumentWriter_English.documents - sender: MetadataRouter.german receiver: DocumentWriter_German.documents inputs: # Define the inputs for your pipeline files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents for language classification. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents with an added `language` metadata field. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `languages` | Optional[List[str]] | None | A list of ISO language codes you want to classify your documents by. For a list of supported languages, see the [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). If not specified, defaults to `["en"]`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents for language classification. | --- ## LLMDocumentContentExtractor Extract textual content from image-based documents using a vision-enabled LLM. ## Key Features - Converts image-based documents (such as scanned PDFs or images) to text using a vision LLM. - Works with any vision-capable `ChatGenerator`. - Processes documents in parallel using a configurable thread pool. - Returns failed documents separately with `content_extraction_error` metadata for debugging or reprocessing. - Supports optional image resizing to reduce memory usage and processing time. - Configurable detail level for image processing (for OpenAI models). ## Configuration 1. Drag the `LLMDocumentContentExtractor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select or configure the vision-capable chat generator (LLM) to use for extraction. 4. Go to the **Advanced** tab to configure additional settings: - Enter the prompt with instructions for the LLM on how to extract content from the document image. The prompt must not contain Jinja variables. - Set the `file_path_meta_field` to specify which metadata field contains the file path. - Optionally set the image `detail` level (`auto`, `high`, or `low`) if using an OpenAI model. - Optionally configure `size` to resize images before processing. - Set `raise_on_failure` and `max_workers` as needed. ## Connections `LLMDocumentContentExtractor` receives a list of image-based documents as input, typically from a converter such as `PDFMinerToDocument`. Each document must have a valid file path in its metadata. It outputs two lists: `documents` contains successfully processed documents updated with extracted text content, and `failed_documents` contains documents that could not be processed. Connect `documents` to `DocumentSplitter` or `DocumentWriter` for further processing. ## Source Code To check this component's source code, open [`llm_document_content_extractor.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/extractors/image/llm_document_content_extractor.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml LLMDocumentContentExtractor: type: haystack.components.extractors.image.LLMDocumentContentExtractor init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o prompt: Extract all text content from this document image. Preserve the original structure including headings, paragraphs, lists, and tables. Return only the extracted text without any additional commentary. file_path_meta_field: file_path detail: auto raise_on_failure: false max_workers: 3 ``` `LLMDocumentContentExtractor` accepts a list of image-based documents as input. Each document must have a valid file path in its metadata. It outputs successfully processed documents (with extracted text content) and a separate list of `failed_documents` for documents the LLM could not process. It typically receives documents from converters such as `PDFMinerToDocument` and sends processed documents to `DocumentSplitter` for further processing. ### Using the component in a pipeline This index uses `LLMDocumentContentExtractor` to extract text from image-based documents (such as scanned PDFs or images) using a vision-enabled LLM: ```yaml # haystack-pipeline components: PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: LLMDocumentContentExtractor: type: haystack.components.extractors.image.LLMDocumentContentExtractor init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o generation_kwargs: prompt: "Extract all text content from this document image. Preserve the original structure including headings, paragraphs, lists, and tables. Return only the extracted text without any additional commentary." file_path_meta_field: file_path detail: auto size: raise_on_failure: false max_workers: 3 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false policy: WRITE connections: - sender: PDFMinerToDocument.documents receiver: LLMDocumentContentExtractor.documents - sender: LLMDocumentContentExtractor.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: DocumentWriter.documents inputs: files: - PDFMinerToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of image-based documents to process. Each document must have a valid file path in its metadata. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Successfully processed documents, updated with extracted content. | | `failed_documents` | List[Document] | Documents that failed processing, annotated with failure metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `chat_generator` | ChatGenerator | | A ChatGenerator instance representing the LLM used to extract text. This generator must support vision-based input and return a plain text response. | | `prompt` | str | DEFAULT_PROMPT_TEMPLATE | Instructional text provided to the LLM. It must not contain Jinja variables. The prompt should only contain instructions on how to extract the content of the image-based document. | | `file_path_meta_field` | str | file_path | The metadata field in the Document that contains the file path to the image or PDF. | | `root_path` | Optional[str] | None | The root directory path where document files are located. If provided, file paths in document metadata will be resolved relative to this path. If None, file paths are treated as absolute paths. | | `detail` | Optional[Literal] | None | Optional detail level of the image (only supported by OpenAI). Can be `"auto"`, `"high"`, or `"low"`. This will be passed to `chat_generator` when processing the images. | | `size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. This reduces file size, memory usage, and processing time. | | `raise_on_failure` | bool | False | If True, exceptions from the LLM are raised. If False, failed documents are logged and returned. | | `max_workers` | int | 3 | Maximum number of threads used to parallelize LLM calls across documents using a ThreadPoolExecutor. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of image-based documents to process. Each must have a valid file path in its metadata. | --- ## LLMMetadataExtractor Automatically extract and enrich document metadata using a large language model. `LLMMetadataExtractor` sends each document to an LLM with a prompt you define, then parses the LLM's response to add new metadata fields to the document. Use this component in indexing pipelines where you want to generate structured metadata from unstructured document content—for example, extracting topics, sentiment, named entities, or any other information your prompt targets. *** ## Key Features - Enriches documents with LLM-generated metadata during indexing. The metadata is generated based on the document content. - Supports any model provider you have connected to the platform. - Lets you define a custom prompt to control what metadata is extracted. - Handles JSON parsing of the LLM response and maps fields directly to document metadata. - Works with all major providers, including Amazon Bedrock, OpenAI, Azure OpenAI, and others. ## Configuration 1. In Builder, click **Add** and find `LLMMetadataExtractor` in the list of components. 2. Drag and drop the component onto the canvas. 3. Click the component to open its configuration. 4. On the **General** tab, configure the following: - **Model**: The model to use for the LLM. - **Prompt**: The prompt instructing the LLM what to extract. Write a prompt that instructs the model to return a JSON object whose keys become the metadata fields added to each document. Use `{{ document.content }}` in the prompt to reference the document content. Example: ``` Extract the following from the document and return as JSON: - topic: the main subject of the document - sentiment: positive, negative, or neutral - language: the language the document is written in ``` 5. Go to the **Advanced** tab to configure additional settings: - **Raise on Failure**: If enabled, raises an exception when extraction fails for a document instead of routing it to `failed_documents`. It's disabled by default. - **Max workers**: The maximum number of workers to use in the thread pool executor. Use this setting to limit the maximum number of requests allowed to run concurrently. - **Expected Keys**: The JSON keys expected in the LLM response. These become the metadata field names. - **Page range**: The range of pages to extract metadata from. Use this setting to limit the number of pages the LLM processes. ## Connections `LLMMetadataExtractor` is designed for indexing pipelines. Typical connections: - **Input**: Receives documents from a `Converter` or `DocumentSplitter`. - **Output**: Passes enriched documents to a `DocumentWriter` or another processing component. ## Source Code To check this component's source code, open [`llm_metadata_extractor.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/extractors/llm_metadata_extractor.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml LLMMetadataExtractor: type: haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o-mini generation_kwargs: max_tokens: 500 temperature: 0.0 response_format: type: json_object prompt: | Extract the following metadata from the document and return it as JSON: - "title": The title or main topic of the document - "entities": A list of named entities (people, organizations, locations) mentioned - "summary": A brief one-sentence summary of the content Document content: {{ document.content }} Return only valid JSON with the keys: title, entities, summary expected_keys: - title - entities - summary raise_on_failure: false max_workers: 3 ``` ### Using the Component in an Index This index uses `LLMMetadataExtractor` to extract structured metadata from documents before splitting and storing them: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 LLMMetadataExtractor: type: haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o-mini generation_kwargs: max_tokens: 500 temperature: 0.0 response_format: type: json_object prompt: | Extract the following metadata from the document and return it as JSON: - "title": The title or main topic of the document - "entities": A list of named entities (people, organizations, locations) mentioned - "summary": A brief one-sentence summary of the content Document content: {{ document.content }} Return only valid JSON with the keys: title, entities, summary expected_keys: - title - entities - summary raise_on_failure: false max_workers: 3 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: LLMMetadataExtractor.documents - sender: LLMMetadataExtractor.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | — | List of documents to extract metadata from. | | `page_range` | List[str \| int] \| None | None | A range of pages to extract metadata from. For example, `['1', '3']` extracts metadata from the first and third pages of each document. Also accepts printable range strings, for example `['1-3', '5', '8', '10-12']` extracts from pages 1, 2, 3, 5, 8, 10, 11, and 12. If None, metadata is extracted from the entire document. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents that were successfully updated with the extracted metadata. | | `failed_documents` | List[Document] | Documents that failed to extract metadata. These documents have `metadata_extraction_error` and `metadata_extraction_response` in their metadata and can be re-run with the extractor. | ### Init Parameters | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `prompt` | str | — | The prompt sent to the LLM for each document. It must contain exactly one variable called `document`, which points to a single document in the list. For example, use `{{ document.content }}` to access the document content. | | `chat_generator` | ChatGenerator | — | A ChatGenerator instance representing the LLM. The LLM must be configured to return a JSON object. For example, when using `OpenAIChatGenerator`, pass `{"response_format": {"type": "json_object"}}` in `generation_kwargs`. | | `expected_keys` | List[str] | None | The keys expected in the JSON output from the LLM. These become the metadata field names added to each document. | | `page_range` | List[str \| int] \| None | None | A range of pages to extract metadata from. For example, `['1', '3']` extracts metadata from the first and third pages of each document. Also accepts printable range strings, for example `['1-3', '5', '8', '10-12']` extracts from pages 1, 2, 3, 5, 8, 10, 11, and 12. If None, metadata is extracted from the entire document. Can be overridden in the `run` method. | | `raise_on_failure` | bool | False | Whether to raise an error on failure during the execution of the generator or validation of the JSON output. If False, failed documents are returned in `failed_documents`. | | `max_workers` | int | 3 | The maximum number of workers to use in the thread pool executor. Limits the maximum number of requests allowed to run concurrently when using the `run_async` method. | ### Run Method Parameters | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | — | The documents to process. | | `page_range` | List[str \| int] \| None | None | A range of pages to extract metadata from. Overrides the `page_range` set at initialization. If None, uses the init parameter value, or extracts metadata from the entire document when not set. | ## Related Information - [Connect to Model and Service Providers](/docs/how-to-guides/managing-access/connect-with-model-providers.mdx) - [Troubleshoot Pipelines and Indexes](/docs/how-to-guides/designing-your-pipeline/troubleshooting-pipeline-deployment.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) --- ## NamedEntityExtractor Annotate named entities in documents and store them as the document's metadata. ## Key Features - Identifies named entities (people, organizations, locations, and other named items) in document text. - Stores entity annotations as metadata in the processed documents. - Supports two backends: Hugging Face and spaCy. - Works with any sequence classification model from the [Hugging Face model hub](https://huggingface.co/models) or any [spaCy model](https://spacy.io/models) with an NER component. - Automatically groups recognized entities by class based on the model used. ## Configuration 1. Drag the `NamedEntityExtractor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Choose the backend: `hugging_face` or `spacy`. - Enter the model name or path. For Hugging Face, use model IDs like `dslim/bert-base-NER`. For spaCy, use model names like `en_core_web_sm`. 4. Go to the **Advanced** tab to configure additional settings: - Optionally set `pipeline_kwargs` to pass additional arguments to the model pipeline. - Configure `device` to specify where to load the model. - Set the `token` for downloading private Hugging Face models. ## Connections `NamedEntityExtractor` receives a list of documents as input, typically from a converter such as `TextFileToDocument` or from `DocumentSplitter`. It outputs a list of documents with named entity annotations stored in their metadata. Connect its output to a document embedder or directly to `DocumentWriter` for storage. ## Source Code To check this component's source code, open [`named_entity_extractor.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/extractors/named_entity_extractor.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml NamedEntityExtractor: type: haystack.components.extractors.named_entity_extractor.NamedEntityExtractor init_parameters: backend: hugging_face model: dslim/bert-base-NER token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false ``` ### Using the Component in an Index This index uses `NamedEntityExtractor` to annotate named entities in documents before storing them: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 NamedEntityExtractor: type: haystack.components.extractors.named_entity_extractor.NamedEntityExtractor init_parameters: backend: hugging_face model: dslim/bert-base-NER pipeline_kwargs: device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: NamedEntityExtractor.documents - sender: NamedEntityExtractor.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | Documents to process. | | `batch_size` | int | 1 | Batch size used for processing the documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Processed documents with named entity annotations stored in metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `backend` | Union[str, NamedEntityExtractorBackend] | | Backend to use for NER. Options: `hugging_face` or `spacy`. | | `model` | str | | Name of the model or a path to the model on the local disk. For Hugging Face, use model IDs like `dslim/bert-base-NER`. For spaCy, use model names like `en_core_web_sm`. | | `pipeline_kwargs` | Optional[Dict[str, Any]] | None | Keyword arguments passed to the pipeline. The pipeline can override these arguments. Dependent on the backend. | | `device` | Optional[ComponentDevice] | None | The device on which the model is loaded. If `None`, the default device is automatically selected. If a device or device map is specified in `pipeline_kwargs`, it overrides this parameter (only applicable to the Hugging Face backend). | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token to download private models from Hugging Face. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | Documents to process. | | `batch_size` | int | 1 | Batch size used for processing the documents. | --- ## RegexTextExtractor Extract text from chat messages or strings using a regex pattern. ## Key Features - Extracts specific text from strings or `ChatMessage` lists using a regular expression pattern. - Supports capture groups to isolate exactly the text you need. - Returns the entire match when no capture group is defined. - Configurable behavior when no match is found: return an empty string or skip output. - Useful for parsing structured output from LLMs, such as URLs, codes, or tagged content. ## Configuration 1. Drag the `RegexTextExtractor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the regular expression pattern to use for extraction. Include a capture group to extract only the desired text. For example, `` captures the URL from the tag. 4. Go to the **Advanced** tab to configure additional settings: - Set `return_empty_on_no_match` to control what happens when the pattern finds no match. ## Connections `RegexTextExtractor` accepts either a string or a list of `ChatMessage` objects as input. Connect it to the `Input` component or to any component that produces `string` or `ChatMessage` output, such as `LLM`. Connect its `captured_text` output to any component that consumes a text string. ## Source Code To check this component's source code, open [`regex_text_extractor.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/extractors/regex_text_extractor.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml RegexTextExtractor: type: haystack.components.extractors.regex_text_extractor.RegexTextExtractor init_parameters: regex_pattern: return_empty_on_no_match: true ``` ### In a Pipeline This query pipeline uses an `LLM` to analyze text and produce structured output, then uses `RegexTextExtractor` to extract a specific issue URL from the response: ```yaml # haystack-pipeline components: RegexTextExtractor: type: haystack.components.extractors.regex_text_extractor.RegexTextExtractor init_parameters: regex_pattern: '' AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a helpful assistant that identifies issues in text. When you find an issue, format your response as: Description of the issue Analyze the following text and identify any issues: {{ query }} {% endmessage %} required_variables: "*" streaming_callback: connections: - sender: RegexTextExtractor.captured_text receiver: AnswerBuilder.replies - sender: LLM.last_message receiver: RegexTextExtractor.text_or_messages inputs: query: - AnswerBuilder.query - LLM.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` In this example: 1. `LLM` generates a response containing the structured output. 2. `RegexTextExtractor` uses the pattern `` to extract the URL from the response. The capture group `([^"]+)` matches any characters except quotes inside the `url` attribute. 3. `AnswerBuilder` formats the extracted URL as the final answer. ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text_or_messages` | Union[str, List[ChatMessage]] | Either a string or a list of ChatMessage objects to search through. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `captured_text` | str | The matched text if a match is found. Empty string if no match is found and `return_empty_on_no_match=False`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `regex_pattern` | str | | The regular expression pattern used to extract text. The pattern should include a capture group to extract the desired text. Example: `''` captures the URL from the tag. | | `return_empty_on_no_match` | bool | True | If True, returns an empty dictionary when no match is found. If False, returns `{"captured_text": ""}`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text_or_messages` | Union[str, List[ChatMessage]] | Either a string or a list of ChatMessage objects to search through. | --- ## Extract Overview # Extract Group Use components in this group to pull structured information out of text. Use them when you want to enrich documents with metadata (for example language, entities, or custom fields) or extract specific content that you can store, filter on, or feed into downstream steps. This subgroup is useful both during indexing and at query time. Extracted fields can improve retrieval and ranking, support metadata filters, and make your pipeline outputs easier to evaluate and debug. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## AnswerBuilder Convert a query and Generator's replies into `GeneratedAnswer` objects. Use it as the last component in query pipelines. :::info This component is no longer needed in most cases. You can connect `LLM`, `Agent`, or a Generator directly to the `Output` component. ::: ## Key Features - Converts a user query and Generator replies into structured `GeneratedAnswer` objects. - Works with both string-based Generators and `ChatMessage`-based Chat Generators. - Supports regex-based answer extraction from Generator output. - Optionally attaches documents and metadata from the Generator to the answer. - Supports reference patterns to link specific documents to the answer. - Supports expanding reference ranges (for example, `[6-10]`) into individual document references. - Configurable to use only the last message or all messages as the answer. ## Configuration 1. Drag the `AnswerBuilder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Optionally enter a `reference_pattern` to parse document references from the Generator's replies. - Configure `last_message_only` and `return_only_referenced_documents` as needed. - Optionally enter a `pattern` to extract a specific portion of the Generator's reply as the answer text. ## Connections `AnswerBuilder` receives the user query (typically from the `Input` component) and Generator replies. Optionally, it also accepts documents and metadata from a retriever or ranker. Connect its `answers` output to the pipeline `Output` component to surface the final answers. To include references in answers, use [DeepsetAnswerBuilder](/docs/reference/pipeline-components/data-processing/transform/DeepsetAnswerBuilder.mdx). For details on which builder to choose, see [Enable references for generated answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx). ## Source Code To check this component's source code, open [`answer_builder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/builders/answer_builder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true ``` ### In a Pipeline This is a RAG pipeline with `AnswerBuilder`. Note that the answers this pipeline generates won't include references. ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: "You are a technical expert.\nYou answer questions truthfully based on provided documents.\nIf the answer exists in several documents, summarize them.\nIgnore documents that don't contain the answer to the question.\nOnly answer based on the documents provided. Don't make things up.\nIf no information related to the question can be found in the document, say so.\nAlways use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] .\nNever name the documents, only enter a number in square brackets as a reference.\nThe reference must only refer to the number that comes in square brackets after the document.\nOtherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\n\nThese are the documents:\n{%- if documents|length > 0 %}\n{%- for document in documents %}\nDocument [{{ loop.index }}] :\nName of Source File: {{ document.meta.file_name }}\n{{ document.content }}\n{% endfor -%}\n{%- else %}\nNo relevant documents found.\nRespond with \"Sorry, no matching documents were found, please adjust the filters or try a different question.\"\n{% endif %}\n\nQuestion: {{ question }}\nAnswer:" required_variables: variables: llm: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: us.anthropic.claude-sonnet-4-20250514-v1:0 aws_region_name: us-west-2 generation_kwargs: # Enable extended thinking mode. # Note that temperature is not supported for extended thinking mode. thinking: type: enabled budget_tokens: 1024 # min budget for Claude 4.0 Sonnet, increase to allow more thinking max_tokens: 1674 # includes thinking.budget_tokens # include_thinking: False # control whether to include thinking output in the reply, defaults to True if unset # thinking_tag: claudeThinking # set tag to identify thinking output, defaults to "thinking" if unset. If set to null, no tags will be added. attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true connections: # Defines how the components are connected - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: prompt_builder.prompt receiver: llm.messages - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: prompt_builder.documents - sender: llm.replies receiver: AnswerBuilder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "prompt_builder.question" - "AnswerBuilder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" files: - multi_file_converter.sources outputs: # Defines the output of your pipeline documents: "attachments_joiner.documents" # The output of the pipeline is the retrieved documents answers: "AnswerBuilder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The user query. | | `replies` | Union[List[str], List[ChatMessage]] | | The output of the Generator. Can be a list of strings or a list of `ChatMessage` objects. | | `meta` | Optional[List[Dict[str, Any]]] | None | The metadata returned by the Generator. If not specified, the generated answer contains no metadata. | | `documents` | Optional[List[Document]] | None | The documents used as input for the Generator. If specified, they are added to the `GeneratedAnswer` objects. | | `pattern` | Optional[str] | None | A regex pattern to extract the answer text from the Generator's reply. If not specified, the value set at initialization is used. | | `reference_pattern` | Optional[str] | None | A regex pattern to identify document references in the Generator's reply. If not specified, the value set at initialization is used. | | `expand_reference_ranges` | Optional[bool] | None | If `True`, reference ranges such as `[6-10]` in the Generator's reply are expanded to individual document references (documents 6 through 10). If not specified, the value set at initialization is used. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `answers` | List[GeneratedAnswer] | The generated answers, each containing the answer text, the original query, the source documents, and any metadata. | ### Init Parameters | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `pattern` | Optional[str] | None | A regex pattern to extract the answer from the Generator's reply. The first capture group is used as the answer. If `None`, the full reply is used. | | `reference_pattern` | Optional[str] | None | A regex pattern to extract document references from the Generator's reply. If `None`, no references are extracted. | | `last_message_only` | bool | False | If `True`, only the last `ChatMessage` in the reply list is used to extract the answer; all previous messages are ignored. | | `return_only_referenced_documents` | bool | False | If `True`, only documents explicitly referenced in the answer are included in the `GeneratedAnswer`. | | `expand_reference_ranges` | bool | False | If `True`, reference ranges such as `[6-10]` are expanded to individual document references (documents 6 through 10). | ### Run Method Parameters See [Inputs](#inputs) above — all run-method parameters are passed as component inputs. ## Related Information - [DeepsetAnswerBuilder](/docs/reference/pipeline-components/data-processing/transform/DeepsetAnswerBuilder.mdx) - [Enable references for generated answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx) --- ## DeepsetAnswerBuilder Convert Generator replies into `GeneratedAnswer` objects with document references that you can visualize in the interface. ## Key Features - Converts Generator replies into `GeneratedAnswer` objects with document references. - Adds references to the answer's `_references` metadata field for display in the interface. - Supports configurable reference patterns, including the `acm` shortcut. - Optionally extracts content from XML tags in the Generator's reply. - Accepts documents from rankers and attaches them to generated answers. - Works with both Generators and Chat Generators. ## Configuration 1. Drag the `DeepsetAnswerBuilder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Optionally enter a `reference_pattern` to parse document references from the Generator's replies. You can use the shortcut `acm` for the pattern `\[(?:(\d+),?\s*)+\]`. - Optionally enter a `pattern` to extract a specific portion of the Generator's reply as the answer text. - Optionally set `extract_xml_tags` to extract content from specific XML tags in the reply. ## Connections `DeepsetAnswerBuilder` receives the user query from the pipeline `Input` or another component, and it receives replies from a Generator. It also optionally receives documents from a ranker to attach them to generated answers. Connect its `answers` output to the pipeline `Output` component to surface the final answers with references. ## Usage Examples ### Basic Configuration ```yaml DeepsetAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: {} ``` ### Using the Component in a Pipeline In this example, `DeepsetAnswerBuilder` receives documents from a ranker and replies from an LLM. It converts the replies into `GeneratedAnswer` objects with document references. ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default top_k: 10 ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: cross-encoder/ms-marco-MiniLM-L-6-v2 top_k: 5 llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o-mini api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false user_prompt: |- {% message role="user" %} Answer the question based on the documents. {% for doc in documents %} Document [{{ loop.index }}]: {{ doc.content }} {% endfor %} Question: {{ query }} {% endmessage %} required_variables: - query - documents answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: llm.documents - sender: llm.last_message receiver: answer_builder.replies inputs: query: - retriever.query - ranker.query - llm.query - answer_builder.query outputs: answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query used in the prompts for the Generator. If `DeepsetAnswerBuilder` doesn't receive the query from a component it's connected to, you must list it in the `inputs` section of the pipeline YAML under `query`. | | `replies` | List[str] | | The output of the Generator. | | `meta` | Optional[List[Dict[str, Any]]] | None | The metadata returned by the Generator. If not specified, the generated answer contains no metadata. | | `documents` | Optional[List[Document]] | None | The documents used as input to the Generator. If `documents` are specified, they are added to the `Answer` objects. If both `documents` and `reference_pattern` are specified, the documents referenced in the Generator's output are extracted from the input documents and added to the `Answer` objects. | | `pattern` | Optional[str] | None | The regular expression pattern to use to extract the answer text from the generator output. If not specified, the whole string is used as the answer. The regular expression can have at most one capture group. If a capture group is present, the text matched by the capture group is used as the answer. If no capture group is present, the whole match is used as the answer. Examples: `[^\n]+$` finds "this is an answer" in a string "this is an argument.\nthis is an answer". `Answer: (.*)` finds "this is an answer" in a string "this is an argument. Answer: this is an answer". | | `reference_pattern` | Optional[str] | None | The regular expression pattern to use for parsing the document references. It's assumed that references are specified as indices of the input documents and that indices start at 1. Example: `\[(\d+)\]` finds "1" in a string "this is an answer[1]". If not specified, no parsing is done, and all documents are referenced. You can use the following shortcuts: - "acm": `\[(?:(\d+),?\s*)+\]` finds "1" and "2" in a string "this is an answer[1, 2]". | | `prompt` | Optional[str] | None | The prompt used in the Generator. If specified, it is added to the metadata of the `Answer` objects. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `answers` | List[GeneratedAnswer] | The answers obtained from the output of the Generator. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `pattern` | Optional[str] | None | The regular expression pattern to use to extract the answer text from the generator output. If not specified, the whole string is used as the answer. The regular expression can have at most one capture group. If a capture group is present, the text matched by the capture group is used as the answer. If no capture group is present, the whole match is used as the answer. Examples: `[^\n]+$` finds "this is an answer" in a string "this is an argument.\nthis is an answer". `Answer: (.*)` finds "this is an answer" in a string "this is an argument. Answer: this is an answer". | | `reference_pattern` | Optional[str] | None | The regular expression pattern to use for parsing the document references. We assume that references are specified as indices of the input documents and that indices start at 1. Example: `\[(\d+)\]` finds "1" in a string "this is an answer[1]". If not specified, no parsing is done, and all documents are referenced. You can use the following shortcuts: - "acm": `\[(?:(\d+),?\s*)+\]` finds "1" and "2" in a string "this is an answer[1, 2]". | | `extract_xml_tags` | Optional[List[str]] | None | A list of XML tags to extract content from. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query used in the prompts for the Generator. | | `replies` | List[str] | | The output of the Generator. | | `meta` | Optional[List[Dict[str, Any]]] | None | The metadata returned by the Generator. If not specified, the generated answer will contain no metadata. | | `documents` | Optional[List[Document]] | None | The documents used as input to the Generator. If `documents` are specified, they are added to the `Answer` objects. If both `documents` and `reference_pattern` are specified, the documents referenced in the Generator output are extracted from the input documents and added to the `Answer` objects. | | `pattern` | Optional[str] | None | The regular expression pattern to use to extract the answer text from the generator output. If not specified, the whole string is used as the answer. The regular expression can have at most one capture group. If a capture group is present, the text matched by the capture group is used as the answer. If no capture group is present, the whole match is used as the answer. Examples: `[^\n]+$` finds "this is an answer" in a string "this is an argument.\nthis is an answer". `Answer: (.*)` finds "this is an answer" in a string "this is an argument. Answer: this is an answer". | | `reference_pattern` | Optional[str] | None | The regular expression pattern to use for parsing the document references. We assume that references are specified as indices of the input documents and that indices start at 1. Example: `\[(\d+)\]` finds "1" in a string "this is an answer[1]". If not specified, no parsing is done, and all documents are referenced. You can use the following shortcuts: - "acm": `\[(?:(\d+),?\s*)+\]` finds "1" and "2" in a string "this is an answer[1, 2]". | | `prompt` | Optional[str] | None | The prompt used in the Generator. If specified, it is added to the metadata of the `Answer` objects. | --- ## DeepsetStaticAnswerBuilder Generate a fixed response text every time it runs. Use it to provide fallback or default answers in conditional pipelines. ## Key Features - Returns a fixed, pre-configured answer text for every pipeline run. - Useful for fallback paths in branching pipelines, such as returning a default message when a query is rejected or a condition is not met. - Optionally attaches documents to the generated answer. - Supports adding custom metadata to the answer using a configurable key-value pair. ## Configuration 1. Drag the `DeepsetStaticAnswerBuilder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the `answer_text` — the fixed response text to return. 4. Go to the **Advanced** tab to configure additional settings: - Optionally set `custom_meta_key` and `custom_meta_value` to add custom metadata to the generated answer. ## Connections `DeepsetStaticAnswerBuilder` receives a query string as input. If it doesn't receive the query from a connected component, list it in the `inputs` section of the pipeline YAML. Optionally, it also accepts documents to include in the answer. Connect its `answers` output to the pipeline `Output` component to surface the fixed response. ## Usage Examples ### Basic Configuration ```yaml DeepsetStaticAnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.static_answer_builder.DeepsetStaticAnswerBuilder init_parameters: {} ``` ### Using the Component in the Pipeline This is an example pipeline where the Router classifies queries into injections and legitimate queries. It sends the injections to `DeepsetStaticAnswerBuilder`, which returns "Cannot answer", while the legitimate queries go to `OutputAdapter`. ```yaml # haystack-pipeline components: # ... router: type: haystack.components.routers.transformers_text_router.TransformersTextRouter init_parameters: model: "JasperLS/deberta-v3-base-injection" labels: ["LEGIT", "INJECTION"] answer_builder: type: deepset_cloud_custom_nodes.augmenters.static_answer_builder.DeepsetStaticAnswerBuilder init_parameters: answer_text: "Cannot answer" custom_meta_key: "error_code" custom_meta_value: "403" output_adapter: type: haystack.components.converters.OutputAdapter init_parameters: output_type: str template: > "Good question: {{query}}" connections: # Defines how the components are connected # ... - sender: router.INJECTION receiver: answer_builder.query - sender: router.LEGIT receiver: output_adapter.query ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query string. If `DeepsetStaticAnswerBuilder` doesn't receive the query from a component it's connected to, you must list it in the `inputs` section of the pipeline YAML under `query`. | | `documents` | Optional[List[Document]] | None | Documents to add to the answer. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `answers` | List[GeneratedAnswer] | A list of GeneratedAnswer objects. Each answer contains the answer text, the query, the documents (if provided), and custom metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `answer_text` | str | | The text of the `GeneratedAnswer` this component outputs. | | `custom_meta_key` | Optional[str] | None | The key for a custom metadata field to be included in the answer. | | `custom_meta_value` | Optional[str] | None | The value for a custom metadata field to be included in the answer. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query string. If `DeepsetStaticAnswerBuilder` doesn't receive the query from a component it's connected to, you must list it in the `inputs` section of the pipeline YAML under `query`. | | `documents` | Optional[List[Document]] | None | Documents to add to the answer. | --- ## JsonSchemaValidator Validate the JSON content of `ChatMessage` objects against a specified [JSON Schema](https://json-schema.org/). ## Key Features - Validates the JSON content of the last message in a list of `ChatMessage` objects against a JSON schema. - Routes valid messages to the `validated` output and invalid messages to the `validation_error` output. - Returns structured error messages when validation fails, which can be fed back to an LLM for correction. - Supports custom error templates for formatting validation error messages. - Enables LLM recovery loops where the LLM retries producing valid JSON output. ## Configuration 1. Drag the `JsonSchemaValidator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. Configure the component settings: - Optionally enter a `json_schema` to validate messages against. - Optionally enter a custom `error_template` to format validation error messages. ## Connections `JsonSchemaValidator` receives a list of `ChatMessage` objects, typically from an LLM or `ChatGenerator`. It validates the last message in the list. Connect its `validated` output to the next component in your pipeline. Connect its `validation_error` output back to a branch joiner that feeds into the LLM to enable retry loops. ## Source Code To check this component's source code, open [`json_schema.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/validators/json_schema.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml JsonSchemaValidator: type: haystack.components.validators.json_schema.JsonSchemaValidator init_parameters: {} ``` ### In a Pipeline This pipeline uses an LLM to extract structured information and return it as JSON. `JsonSchemaValidator` validates the output against a schema. If validation fails, the error is sent back to the LLM through a `BranchJoiner` so the LLM can correct its output. ```yaml # haystack-pipeline components: branch_joiner: type: haystack.components.joiners.branch.BranchJoiner init_parameters: type_: "typing.List[haystack.dataclasses.ChatMessage]" prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: | Extract the following information from the text and return it as valid JSON. Text: {{ query }} Return a JSON object with these fields: - "answer": a concise answer to the query (string) - "confidence": a confidence score between 0 and 1 (number) _role: user llm: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o-mini json_validator: type: haystack.components.validators.json_schema.JsonSchemaValidator init_parameters: json_schema: type: object properties: answer: type: string confidence: type: number minimum: 0 maximum: 1 required: - answer - confidence connections: - sender: branch_joiner.value receiver: prompt_builder.messages - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: json_validator.messages - sender: json_validator.validation_error # Retry loop: send errors back to the LLM receiver: branch_joiner.value inputs: query: - prompt_builder.query outputs: validated_response: json_validator.validated ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances to be validated. The last message in this list is the one that is validated. | | `json_schema` | Optional[Dict[str, Any]] | None | A dictionary representing the [JSON schema](https://json-schema.org/) against which the messages' content is validated. If not provided, the schema from the component init is used. | | `error_template` | Optional[str] | None | A custom template string for formatting the error message in case of validation. If not provided, the `error_template` from the component init is used. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `validated` | List[ChatMessage] | A list of messages if the last message is valid. | | `validation_error` | List[ChatMessage] | A list of messages if the last message is invalid. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `json_schema` | Optional[Dict[str, Any]] | None | A dictionary representing the [JSON schema](https://json-schema.org/) against which the messages' content is validated. | | `error_template` | Optional[str] | None | A custom template string for formatting the error message in case of validation failure. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances to be validated. The last message in this list is the one that is validated. | | `json_schema` | Optional[Dict[str, Any]] | None | A dictionary representing the [JSON schema](https://json-schema.org/) against which the messages' content is validated. If not provided, the schema from the component init is used. | | `error_template` | Optional[str] | None | A custom template string for formatting the error message in case of validation. If not provided, the `error_template` from the component init is used. | --- ## OutputAdapter Adapt output of components using Jinja templates. This is useful if you want to connect components that have different input or output types. :::tip You may not need this component With [smart connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections), the pipeline automatically converts between `String` and `ChatMessage` in both directions. If you're using `OutputAdapter` just for this type conversion, you can remove it. For details, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ::: ## Key Features - Adapts component outputs to match the expected input types of downstream components using Jinja2 templates. - The template variables define the component's inputs dynamically. - Supports custom Jinja filters for advanced transformations. - Safe mode by default, with an optional `unsafe` setting for complex types such as `ChatMessage`, `Document`, or `Answer`. ## Configuration 1. Drag the `OutputAdapter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Jinja2 `template` that defines how to transform the input. The variables used in the template become the component's inputs. For example, the template `{{ documents[0].content }}` creates a `documents` input. - Set the `output_type` to specify the type of the transformed output. 4. Go to the **Advanced** tab to configure additional settings: - Optionally add `custom_filters` for custom Jinja filter functions. - Enable `unsafe` mode if you need to work with complex types like `ChatMessage`, `Document`, or `Answer`. Use this with caution as it may allow remote code execution. ## Connections `OutputAdapter` accepts any inputs defined by the variables in its `template`. Connect the output of an upstream component to the matching template variable input. Connect its output to any downstream component that expects the transformed type. For details and examples, see the [Incompatible Connection Types](/docs/concepts/about-pipelines/non-standard-component-connections.mdx) section. ## Source Code To check this component's source code, open [`output_adapter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/output_adapter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml replies_to_query: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: str ``` ### Using the Component in a Pipeline This is an example of a RAG chat pipeline where `OutputAdapter` converts LLM's replies into a single string that other components can accept. ```yaml # haystack-pipeline components: LLM: init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator required_variables: '*' streaming_callback: system_prompt: '' user_prompt: >- {% message role="user" %} You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ query }} New question: {% endmessage %} type: haystack.components.generators.chat.llm.LLM answer_builder: init_parameters: reference_pattern: acm type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder bm25_retriever: init_parameters: document_store: init_parameters: create_index: true embedding_dim: 768 hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} index: Standard-Index-English mappings: max_chunk_bytes: 104857600 method: return_embedding: false settings: index.knn: true similarity: cosine timeout: use_ssl: true verify_certs: false type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever document_joiner: init_parameters: join_mode: concatenate type: haystack.components.joiners.document_joiner.DocumentJoiner embedding_retriever: init_parameters: document_store: init_parameters: create_index: true embedding_dim: 768 hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} index: Standard-Index-English mappings: max_chunk_bytes: 104857600 method: return_embedding: false settings: index.knn: true similarity: cosine timeout: use_ssl: true verify_certs: false type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever query_embedder: init_parameters: model: intfloat/e5-base-v2 type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder ranker: init_parameters: model: intfloat/simlm-msmarco-reranker model_kwargs: torch_dtype: torch.float16 top_k: 8 type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker LLM_2: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.5 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: "" user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ query }} Answer: {% endmessage %} required_variables: "*" streaming_callback: connections: - receiver: document_joiner.documents sender: bm25_retriever.documents - receiver: embedding_retriever.query_embedding sender: query_embedder.embedding - receiver: document_joiner.documents sender: embedding_retriever.documents - receiver: ranker.documents sender: document_joiner.documents - receiver: answer_builder.documents sender: ranker.documents - sender: LLM.last_message receiver: query_embedder.text - sender: LLM.last_message receiver: bm25_retriever.query - sender: LLM.last_message receiver: ranker.query - sender: LLM.last_message receiver: answer_builder.replies - sender: LLM.messages receiver: LLM_2.messages - sender: ranker.documents receiver: LLM_2.documents - sender: LLM_2.last_message receiver: answer_builder.replies inputs: filters: - bm25_retriever.filters - embedding_retriever.filters query: - LLM.query max_runs_per_component: 100 metadata: {} outputs: answers: answer_builder.answers documents: ranker.documents ``` ## Parameters ### Inputs Input names and types depend on how you configure the `template` parameter. | Parameter | Type | Description | | :-------- | :--- | :---------- | | `kwargs` | Any | Must contain all variables used in the `template` string. | ### Outputs The output depends on the value of the `output_type` parameter. ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `template` | str | | A Jinja template that defines how to adapt the input data. The variables in the template define the input of this instance. For example, with this template: `{{ documents[0].content }}`, the component input will be `documents`. | | `output_type` | TypeAlias | | The type of output this instance should return. | | `custom_filters` | Optional[Dict[str, Callable]] | None | A dictionary of custom Jinja filters used in the template. | | `unsafe` | bool | False | Enable execution of arbitrary code in the Jinja template. This should only be used if you trust the source of the template as it can lead to remote code execution. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :---------- | | `kwargs` | Any | Must contain all variables used in the `template` string. | --- ## Transform Overview # Transform Group Use components in this group to reshape, validate, or assemble data as it moves through your pipeline. Use them to enforce output formats, adapt results to the next step, and build structured outputs such as answers from retrieved content and model responses. This subgroup is most common in the middle or end of a pipeline, where you want predictable, consistent outputs for your app or API. It is also useful when you integrate LLMs and need validation or post-processing to keep outputs machine-readable. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## Data Processing # Data Processing Components Data Processing components help you prepare data before you store it, retrieve it, or pass it to AI components. Use this group to turn raw inputs into clean, well-structured documents, enrich them with metadata, and shape content so it works well with downstream steps such as embedding, retrieval, ranking, and generation. The group is split into four subgroups that cover the most common stages of preprocessing: - **Clean & split**: Remove noise and split large documents into smaller chunks that fit your retrieval strategy. - **Convert**: Turn files or links into content you can process in a pipeline (for example, fetch content from a URL or wrap file contents). - **Extract**: Pull structured information from text, such as metadata, entities, language, or targeted fields. - **Transform**: Validate, reshape, or build outputs from pipeline results (for example, validate JSON outputs or build answers). ## Subgroups Use these pages to explore the components in each subgroup: - Clean & split - Convert - Transform - Extract --- ## DeepsetFileUploader Upload files from your pipeline to temporary file storage and return stable references (`file_id` and `file_name`) you can expose as pipeline output, so people can download those files from the product. Think of the component as a handoff step: your pipeline or another component already has files, for example a generated spreadsheet or a chart saved to disk. Those files live on the worker where the pipeline ran. `DeepsetFileUploader` copies them to the platform and gives back IDs the UI and APIs understand, so the same run can offer downloadable attachments instead of only text. ## Key Features - Uploads files to temporary file storage during a pipeline run. - Returns stable `file_id` and `file_name` references for each uploaded file. - Supports local file paths, `Path` objects, and in-memory `ByteStream` objects. - Exposes uploaded files as downloadable attachments in Playground, jobs, and integrated apps. - Requires no init parameters — all settings use environment variables. ## Configuration Before using `DeepsetFileUploader`, create the following secrets in the workspace or organization: - `DEEPSET_API_URL`: The base URL of the deepset API. Set it to `https://api.cloud.deepset.ai`. - `DEEPSET_API_KEY`: The API key to connect to your workspace or organization. For details, see [Generate API Keys](/docs/how-to-guides/managing-access/generate-api-key.mdx). Optionally, set the workspace name in the `DEEPSET_WORKSPACE` secret. If omitted, the component uses `default`. For instructions on creating secrets, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 1. Drag the `DeepsetFileUploader` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. The component has no configuration options in Pipeline Builder. All settings come from the environment variables listed above. 1. Drag the `DeepsetFileUploader` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. The component has no parameters to configure in the panel. Authentication and workspace selection use the environment variables above. ## Connections `DeepsetFileUploader` receives files from any component that produces a list of strings, paths, or `ByteStream` objects. Connect its `files` output to the `Output` component so users can download the uploaded files from the platform. ## Usage Examples ### Basic Configuration ```yaml file_uploader: type: deepset_cloud_custom_nodes.utils.deepset_file_uploader.DeepsetFileUploader init_parameters: {} ``` ### Basic `DeepsetFileUploader` Configuration This is the basic component configuration. The component has no parameters, so you just specify the component type and leave the init parameters empty. ```yaml # haystack-pipeline components: file_uploader: type: deepset_cloud_custom_nodes.utils.deepset_file_uploader.DeepsetFileUploader init_parameters: {} ``` ### Pipeline Where Another Component Creates Files This is an example of a pipeline where a custom component writes files to disk and exposes a list of paths that should become downloads. ```yaml components: report_exporter: type: my_org.custom_nodes.report_exporter.ReportExporter init_parameters: output_format: csv file_uploader: type: deepset_cloud_custom_nodes.utils.deepset_file_uploader.DeepsetFileUploader init_parameters: {} connections: - sender: report_exporter.saved_paths receiver: file_uploader.files inputs: query: - "report_exporter.query" outputs: attachments: "file_uploader.files" max_runs_per_component: 100 metadata: {} ``` `ReportExporter` is an example component that must output `saved_paths` as a list of strings (or paths). The pipeline output key `attachments` maps to the uploader's `files` list so the platform can treat them as downloadable file references. ### Pipeline Where Files Are Supplied at Query Time This is an example of a pipeline where files are supplied at query time. Users upload files to be translated and the pipeline returns the translated files. Note that the `Input` component is configured to accept `files` and `query` inputs, and the `Output` component is configured to output `output_files` and `messages`. ```yaml # haystack-pipeline components: file_uploader: type: deepset_cloud_custom_nodes.utils.deepset_file_uploader.DeepsetFileUploader init_parameters: {} LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: init_parameters: model: gpt-5.4 type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator system_prompt: |- {% message role="system" %} You are a professional translator that translates files. {% endmessage %} user_prompt: |- {% message role="user" %} Translate the following {{ files }} into English. {% endmessage %} required_variables: "*" streaming_callback: connections: [] max_runs_per_component: 100 metadata: {} inputs: files: - file_uploader.files - LLM.files query: - LLM.messages outputs: output_files: file_uploader.files messages: LLM.messages ``` Wire your client or Playground input schema so the pipeline receives a `files` value compatible with the uploader (paths or `ByteStream`-like payloads your platform sends). ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `files` | List[Union[str, Path, ByteStream]] | Files to upload: local paths or in-memory streams. For paths, the file name is taken from the path. For `ByteStream`, set `file_name` in `meta`. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | `files` | List[Dict[str, str]] | One entry per uploaded file: `file_id` (platform ID) and `file_name` (original name). | ### Init Parameters `DeepsetFileUploader` has no init parameters. Authentication and workspace selection use environment variables only. ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `files` | List[Union[str, Path, ByteStream]] | | Files to upload: paths or streams. For `ByteStream`, set `file_name` in `meta`. | --- ## Input The `Input` component is the entry point of every pipeline. It declares which named inputs the pipeline accepts, such as a user query, metadata filters, uploaded files, or chat messages. It then routes each input to the correct component sockets inside the pipeline. Every pipeline must have at least one input. ## Key Features - Defines the external interface of the pipeline (what callers must provide). - Supports standard input types: text queries, metadata filters, files, and chat messages. - Accepts custom-named inputs that map to any compatible component socket. - In Pipeline Builder, each output slot on the `Input` card connects to the downstream components that should receive it. ## Configuration 1. Drag the `Input` component onto the canvas from the **Input & Output** group in the Component Library. 2. Click the component card to add input types the pipeline needs. 3. Connect each output slot to the component socket that should receive it. ## Possible Inputs You can use any of the following standard keys or define your own custom keys: | Input Key | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The user's search query or question. Route it to any component that accepts a string input, such as a retriever or text embedder. | | `filters` | Optional[Dict[str, Any]] | Metadata filters for document retrieval. Route it to the `filters` input of a retriever. | | `files` | List[ByteStream] | Files uploaded at query time. Route it to a file converter or `DeepsetFileUploader`. | | `messages` | List[ChatMessage] | Chat history for conversational pipelines. Route it to a `ChatPromptBuilder` or directly to an LLM. | | `streaming_callback` | Optional[Callable] | A callback function invoked for each streaming token. Route it to the `streaming_callback` input of an LLM or generator. Set it to `deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback` to enable streaming in Playground. | | *custom* | Any | Any name that matches the input socket type of the receiving component. Useful for passing domain-specific parameters at query time. | ## Usage Examples ### Basic Configuration Declare pipeline inputs and connect them to component sockets: ```yaml inputs: query: - retriever.query - llm.query filters: - retriever.filters ``` ### In a RAG Pipeline In a RAG pipeline, you typically need `query` and `filters` inputs. On the `Input` component card, add: ```yaml - query - filters ``` and then connect each input to the component that should receive it. Here is an example of a RAG pipeline: ```yaml # haystack-pipeline # If you need help with the YAML format, have a look at https://docs.cloud.deepset.ai/docs/create-a-pipeline-in-studio . # This section defines components that you want to use in your pipelines. Each component must have a name and a type. You can also set the component's parameters here. # The name is up to you, you can give your component a friendly name. You then use components' names when specifying the connections in the pipeline. # Type is the class path of the component. You can check the type on the component's documentation page. components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id llm: type: haystack.components.generators.chat.llm.LLM init_parameters: # You can swap this for any other model. Switch to the Builder view and choose another model from the list on the component card. chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: "gpt-5.4" generation_kwargs: max_completion_tokens: 650 temperature: 0.0 user_prompt: |- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: llm.last_message receiver: answer_builder.replies - sender: meta_field_grouping_ranker.documents receiver: llm.documents inputs: query: - retriever.query - ranker.query - llm.question - answer_builder.query filters: - retriever.filters_bm25 - retriever.filters_embedding files: [] outputs: answers: answer_builder.answers messages: llm.messages max_runs_per_component: 100 metadata: {} ``` ### File Upload Pipeline If you want a pipeline where users upload files at query time, add `files` to the `Input` component card and connect it to the component that should receive it. Make sure you add a Converter that can preprocess the uploaded files so that the query pipeline can use them.Here is an example: ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: null sort_docs_by: split_id llm: type: haystack.components.generators.chat.llm.LLM init_parameters: # You can swap this for any other model. Switch to the Builder view and choose another model from the list on the component card. chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: "gpt-5.4" generation_kwargs: max_completion_tokens: 650 temperature: 0.0 user_prompt: |- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: llm.last_message receiver: answer_builder.replies - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: llm.documents inputs: query: - "retriever.query" - "ranker.query" - "llm.question" - "answer_builder.query" filters: - "retriever.filters_bm25" - "retriever.filters_embedding" files: - multi_file_converter.sources outputs: documents: "attachments_joiner.documents" answers: "answer_builder.answers" messages: llm.messages ``` --- ## Output Define what your pipeline returns. The `Output` component is the exit point of a pipeline. It declares which named outputs the pipeline exposes, such as retrieved documents, generated messages, or structured answers. Every pipeline should have at least one output. ## Key Features - Defines the final output of the pipeline. - Each named output maps to exactly one component connection. - Supports standard output types: documents, messages, answers, and files. ## Configuration 1. Drag the `Output` component onto the canvas from the **Input & Output** group in the Component Library. 2. Click the component card to add an input slot for each value your pipeline should return. 3. Connect the upstream component socket that produces the output to the corresponding slot. ## Possible Outputs You can use any of the following standard keys or define your own: | Output Key | Type | Description | | :--------- | :--- | :---------- | | `documents` | List[Document] | Retrieved or processed documents. Typically comes from a retriever or ranker. | | `messages` | List[ChatMessage] | LLM-generated responses in chat format. Typically comes from an LLM or `ChatGenerator`. Use `last_message` for a single message or `messages` for the full conversation. | | `answers` | List[Answer] | Structured answer objects from extractive or generative QA components (for example, `ExtractiveReader` or `AnswerBuilder`). | | *custom* | Any | Any name that maps to the output socket of a component. Useful for returning file references, metadata, or other custom payloads. | ## Usage Examples ### Basic Configuration Declare pipeline outputs and map them to component sockets: ```yaml outputs: documents: ranker.documents answers: answer_builder.answers ``` ### Document Search Pipeline For a pipeline that returns retrieved documents, add `documents` to the `Output` component card and connect it to the component that should produce the documents. Here is an example: ```yaml # haystack-pipeline components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents inputs: query: - query_embedder.text - ranker.query filters: - embedding_retriever.filters outputs: documents: ranker.documents max_runs_per_component: 100 metadata: {} ``` ### RAG Pipeline For a pipeline that returns both the generated answer and the source documents, add `documents` and `answers` to the `Output` component card and connect them to the components that should produce the documents and answers. Here is an example: ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id llm: type: haystack.components.generators.chat.llm.LLM init_parameters: # You can swap this for any other model. Switch to the Builder view and choose another model from the list on the component card. chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: "gpt-5.4" generation_kwargs: max_completion_tokens: 650 temperature: 0.0 user_prompt: |- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: {% endmessage %} required_variables: "*" answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: llm.last_message receiver: answer_builder.replies - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: llm.documents inputs: query: - retriever.query - ranker.query - llm.question - answer_builder.query filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources outputs: documents: attachments_joiner.documents answers: answer_builder.answers messages: llm.messages max_runs_per_component: 100 metadata: {} ``` ### Extractive QA Pipeline For a pipeline that returns structured answers, add `answers` to the `Output` component card and connect it to the component that should produce the answers. Here is an example: ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 hosts: index: "" max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 10 reader: type: haystack.components.readers.extractive.ExtractiveReader init_parameters: answers_per_seq: 20 calibration_factor: 1.0 max_seq_length: 384 model: "deepset/deberta-v3-large-squad2" model_kwargs: torch_dtype: "torch.float16" no_answer: false top_k: 10 attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: splitter.documents - sender: pdf_converter.documents receiver: splitter.documents - sender: markdown_converter.documents receiver: splitter.documents - sender: html_converter.documents receiver: splitter.documents - sender: pptx_converter.documents receiver: splitter.documents - sender: docx_converter.documents receiver: splitter.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: attachments_joiner.documents - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: reader.documents inputs: query: - retriever.query - ranker.query - reader.query filters: - retriever.filters_bm25 - retriever.filters_embedding files: - multi_file_converter.sources outputs: documents: attachments_joiner.documents answers: reader.answers max_runs_per_component: 100 metadata: {} ``` --- ## Input and Output Overview # Input and Output Input and Output components handle how data enters and leaves your pipeline in the product, for example uploading generated files so they can be downloaded from a run. Use this section when you need stable file references, handoffs between the worker and the platform, or other boundary components that connect pipeline execution to Playground, jobs, or integrated apps. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## AIMLAPIChatGenerator Generate chat responses using models hosted on the [AI/ML API](https://aimlapi.com/) platform. AI/ML API provides access to hundreds of AI models through a single OpenAI-compatible API. ## Key Features - Access to 200+ AI models from OpenAI, Anthropic, Meta, Mistral, and others through a single endpoint. - Compatible with OpenAI's Chat Completions API format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Configurable retry logic and timeout settings. ## Configuration 1. Drag the `AIMLAPIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the model you want to use (for example, `openai/gpt-4o` or `anthropic/claude-opus-4-5`). For a full list, see the [AI/ML API model catalog](https://aimlapi.com/models). 2. Create a secret with your AI/ML API key and set it as `api_key`. Use `AIMLAPI_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs` such as `max_tokens`, `temperature`, and `top_p`. ## Connections `AIMLAPIChatGenerator` receives a list of `ChatMessage` objects as input, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/aimlapi/src/haystack_integrations/components/generators/aimlapi/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AIMLAPIChatGenerator: type: haystack_integrations.components.generators.aimlapi.chat.chat_generator.AIMLAPIChatGenerator init_parameters: api_key: type: env_var env_vars: - AIMLAPI_API_KEY strict: false model: openai/gpt-4o generation_kwargs: max_tokens: 1024 temperature: 0.7 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: system content: You are a helpful assistant. Answer questions based on the provided documents. - role: user content: | Documents: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack_integrations.components.generators.aimlapi.chat.chat_generator.AIMLAPIChatGenerator init_parameters: api_key: type: env_var env_vars: - AIMLAPI_API_KEY strict: false model: openai/gpt-4o generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question documents: - prompt_builder.documents outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("AIMLAPI_API_KEY")` | The AI/ML API key. | | `model` | str | `openai/gpt-5-chat-latest` | The model to use. Supports any model available in the AI/ML API catalog. | | `api_base_url` | Optional[str] | `https://api.aimlapi.com/v1` | The base URL for the AI/ML API. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. When set, the model streams tokens as they're generated. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters passed to the API, such as `max_tokens`, `temperature`, and `top_p`. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. Falls back to `AIMLAPI_MAX_RETRIES` env var or `5`. | | `extra_headers` | Optional[Dict[str, Any]] | None | Additional HTTP headers to include in requests. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments to pass to the HTTP client. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model, overriding init-time tools. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AlloyDBDocumentStore Store and retrieve documents using [AlloyDB for PostgreSQL](https://cloud.google.com/alloydb), Google Cloud's fully managed, PostgreSQL-compatible database with built-in vector search capabilities. ## Key Features - Stores documents in AlloyDB with full-text and vector search support. - Supports exact nearest neighbor (ENN) and HNSW approximate nearest neighbor (ANN) vector search strategies. - Supports multiple vector similarity functions: cosine similarity, inner product, and L2 distance. - Supports IAM authentication for secure, keyless access. - Configurable connection via public, private, or PSC IP types. ## Configuration 1. Set up the AlloyDB instance and create a database. 2. Set the `ALLOYDB_INSTANCE_URI`, `ALLOYDB_USER`, and `ALLOYDB_PASSWORD` environment variables. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 3. Configure the `AlloyDBDocumentStore` in your pipeline YAML with the appropriate connection parameters and embedding dimension. ## Source Code To check this component's source code, open [`document_store.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/alloydb/src/haystack_integrations/document_stores/alloydb/document_store.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AlloyDBDocumentStore: type: haystack_integrations.document_stores.alloydb.document_store.AlloyDBDocumentStore init_parameters: instance_uri: type: env_var env_vars: - ALLOYDB_INSTANCE_URI strict: true user: type: env_var env_vars: - ALLOYDB_USER strict: true password: type: env_var env_vars: - ALLOYDB_PASSWORD strict: false db: my_database embedding_dimension: 768 ``` ### Using HNSW Index for Approximate Nearest Neighbor Search ```yaml AlloyDBDocumentStore: type: haystack_integrations.document_stores.alloydb.document_store.AlloyDBDocumentStore init_parameters: instance_uri: type: env_var env_vars: - ALLOYDB_INSTANCE_URI strict: true user: type: env_var env_vars: - ALLOYDB_USER strict: true password: type: env_var env_vars: - ALLOYDB_PASSWORD strict: false db: my_database embedding_dimension: 768 search_strategy: hnsw vector_function: cosine_similarity ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `instance_uri` | Secret | `Secret.from_env_var("ALLOYDB_INSTANCE_URI")` | The AlloyDB instance URI. | | `user` | Secret | `Secret.from_env_var("ALLOYDB_USER")` | The database user. | | `password` | Secret | `Secret.from_env_var("ALLOYDB_PASSWORD", strict=False)` | The database password. Not required when using IAM authentication. | | `db` | str | `postgres` | The name of the database to connect to. | | `enable_iam_auth` | bool | `False` | Whether to use IAM authentication. | | `ip_type` | str | `PRIVATE` | The IP type for the connection. One of `PRIVATE`, `PUBLIC`, or `PSC`. | | `create_extension` | bool | `True` | Whether to create the `vector` extension if it doesn't exist. | | `schema_name` | str | `public` | The schema name where the document table is stored. | | `table_name` | str | `haystack_documents` | The name of the table to store documents in. | | `language` | str | `english` | The language used for full-text search indexing. | | `embedding_dimension` | int | `768` | The dimensionality of document embeddings. Must match your embedding model's output. | | `vector_function` | str | `cosine_similarity` | The vector similarity function. One of `cosine_similarity`, `inner_product`, or `l2_distance`. | | `recreate_table` | bool | `False` | Whether to drop and recreate the document table on initialization. | | `search_strategy` | str | `exact_nearest_neighbor` | The vector search strategy. One of `exact_nearest_neighbor` or `hnsw`. | | `hnsw_recreate_index_if_exists` | bool | `False` | Whether to recreate the HNSW index if it already exists. | | `hnsw_index_creation_kwargs` | Optional[Dict[str, int]] | None | Additional keyword arguments for HNSW index creation (for example, `m` and `ef_construction`). | | `hnsw_index_name` | str | `haystack_hnsw_index` | The name of the HNSW index. | | `hnsw_ef_search` | Optional[int] | None | The `ef_search` parameter for HNSW queries. Higher values improve recall at the cost of speed. | | `keyword_index_name` | str | `haystack_keyword_index` | The name of the full-text search index. | ## Related Information - [AlloyDBEmbeddingRetriever](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBEmbeddingRetriever.mdx) - [AlloyDBKeywordRetriever](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBKeywordRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AlloyDBEmbeddingRetriever Retrieve documents from an `AlloyDBDocumentStore` using vector similarity search. Use this component in query pipelines to find semantically similar documents based on dense embeddings. ## Key Features - Performs vector similarity search using embeddings stored in AlloyDB. - Supports cosine similarity, inner product, and L2 distance similarity functions. - Supports exact nearest neighbor (ENN) and HNSW approximate nearest neighbor (ANN) search strategies defined on the document store. - Configurable filter policy to merge or replace filters at query time. ## Configuration 1. First, configure an `AlloyDBDocumentStore` in your pipeline. 2. Drag the `AlloyDBEmbeddingRetriever` component onto the canvas from the Component Library. 3. Connect an embedder component to provide `query_embedding` as input. 4. Connect the retriever output to downstream components such as `PromptBuilder`. ## Connections `AlloyDBEmbeddingRetriever` receives a `query_embedding` (list of floats) from a text embedder such as `SentenceTransformersTextEmbedder`. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/alloydb/src/haystack_integrations/components/retrievers/alloydb/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AlloyDBEmbeddingRetriever: type: haystack_integrations.components.retrievers.alloydb.embedding_retriever.AlloyDBEmbeddingRetriever init_parameters: document_store: AlloyDBDocumentStore top_k: 5 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 document_store: type: haystack_integrations.document_stores.alloydb.document_store.AlloyDBDocumentStore init_parameters: instance_uri: type: env_var env_vars: - ALLOYDB_INSTANCE_URI strict: true user: type: env_var env_vars: - ALLOYDB_USER strict: true password: type: env_var env_vars: - ALLOYDB_PASSWORD strict: false db: my_database embedding_dimension: 384 retriever: type: haystack_integrations.components.retrievers.alloydb.embedding_retriever.AlloyDBEmbeddingRetriever init_parameters: document_store: document_store top_k: 5 connections: - sender: text_embedder.embedding receiver: retriever.query_embedding inputs: query: - text_embedder.text outputs: documents: retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The query embedding vector to search for similar documents. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of the most similar documents from the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AlloyDBDocumentStore | | The AlloyDB document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `vector_function` | Optional[str] | None | Override the document store's vector similarity function. One of `cosine_similarity`, `inner_product`, or `l2_distance`. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding vector to search with. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | | `vector_function` | Optional[str] | None | Override the vector similarity function for this query. | ## Related Information - [AlloyDBDocumentStore](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBDocumentStore.mdx) - [AlloyDBKeywordRetriever](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBKeywordRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AlloyDBKeywordRetriever Retrieve documents from an `AlloyDBDocumentStore` using full-text keyword search. Use this component in query pipelines when you need BM25-style text matching rather than vector similarity search. ## Key Features - Performs full-text search using AlloyDB's native keyword indexing. - Configurable filter policy to merge or replace filters at query time. - Can be combined with `AlloyDBEmbeddingRetriever` in a hybrid search pipeline. ## Configuration 1. First, configure an `AlloyDBDocumentStore` in your pipeline. 2. Drag the `AlloyDBKeywordRetriever` component onto the canvas from the Component Library. 3. Connect the component to a query input and downstream components such as `PromptBuilder`. ## Connections `AlloyDBKeywordRetriever` receives a text `query` string as input. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`keyword_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/alloydb/src/haystack_integrations/components/retrievers/alloydb/keyword_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AlloyDBKeywordRetriever: type: haystack_integrations.components.retrievers.alloydb.keyword_retriever.AlloyDBKeywordRetriever init_parameters: document_store: AlloyDBDocumentStore top_k: 5 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of matching documents from the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AlloyDBDocumentStore | | The AlloyDB document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | ## Related Information - [AlloyDBDocumentStore](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBDocumentStore.mdx) - [AlloyDBEmbeddingRetriever](/docs/reference/pipeline-components/integrations/alloydb/AlloyDBEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AnthropicChatGenerator Generate chat responses using Anthropic's Claude language models. ## Key Features - Supports all Claude models, including Claude Sonnet, Claude Opus, and Claude Haiku. - Accepts and returns messages in `ChatMessage` format. - Supports multimodal inputs, including text and images. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports extended thinking for complex reasoning tasks. ## Configuration 1. Drag the `AnthropicChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Claude model you want to use (for example, `claude-opus-4-5`). For a full list of models, see the [Anthropic documentation](https://docs.anthropic.com/en/docs/about-claude/models/all-models). 2. Create a secret with your Anthropic API key and set it as `api_key`. Use `ANTHROPIC_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs` such as `max_tokens`, `temperature`, `top_p`, and `system`. ## Connections `AnthropicChatGenerator` receives a list of `ChatMessage` objects as input, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AnthropicChatGenerator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: api_key: type: env_var env_vars: - ANTHROPIC_API_KEY strict: false model: claude-opus-4-5 generation_kwargs: max_tokens: 1024 temperature: 0.7 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: system content: You are a helpful assistant. Answer questions based on the provided documents. - role: user content: | Documents: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: api_key: type: env_var env_vars: - ANTHROPIC_API_KEY strict: false model: claude-opus-4-5 generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question documents: - prompt_builder.documents outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("ANTHROPIC_API_KEY")` | The Anthropic API key. | | `model` | str | `claude-sonnet-4-5` | The name of the Claude model to use. For a full list, see the [Anthropic documentation](https://docs.anthropic.com/en/docs/about-claude/models/all-models). | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. When set, the model streams tokens as they're generated. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters passed to the Anthropic API, such as `max_tokens`, `temperature`, `top_p`, `top_k`, `stop_sequences`, and `system`. | | `ignore_tools_thinking_messages` | bool | True | Whether to suppress `thinking` messages from tool use responses. Set to `False` to include them. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model, overriding init-time tools. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ArcadeDBDocumentStore Store and retrieve documents using [ArcadeDB](https://arcadedb.com/), a multi-model database that supports vector similarity search alongside graph, document, and key-value data models. ## Key Features - Stores documents in ArcadeDB with native vector search support. - Supports cosine, Euclidean, and dot product similarity functions. - Supports automatic database and type (collection) creation on initialization. - Configurable embedding dimensions to match your embedding model. ## Configuration 1. Install and run ArcadeDB (default endpoint: `http://localhost:2480`). 2. Set the `ARCADEDB_USERNAME` and `ARCADEDB_PASSWORD` environment variables if authentication is enabled. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 3. Configure the `ArcadeDBDocumentStore` in your pipeline YAML with the appropriate connection parameters. ## Source Code To check this component's source code, open [`document_store.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/arcadedb/src/haystack_integrations/document_stores/arcadedb/document_store.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ArcadeDBDocumentStore: type: haystack_integrations.document_stores.arcadedb.document_store.ArcadeDBDocumentStore init_parameters: url: http://localhost:2480 database: my_haystack_db username: type: env_var env_vars: - ARCADEDB_USERNAME strict: false password: type: env_var env_vars: - ARCADEDB_PASSWORD strict: false embedding_dimension: 768 similarity_function: cosine ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `url` | str | `http://localhost:2480` | The URL of the ArcadeDB server. | | `database` | str | `haystack` | The name of the database to use. | | `username` | Secret | `Secret.from_env_var("ARCADEDB_USERNAME", strict=False)` | The ArcadeDB username. | | `password` | Secret | `Secret.from_env_var("ARCADEDB_PASSWORD", strict=False)` | The ArcadeDB password. | | `type_name` | str | `Document` | The name of the document type (collection) to use. | | `embedding_dimension` | int | `768` | The dimensionality of document embeddings. Must match your embedding model's output. | | `similarity_function` | str | `cosine` | The vector similarity function. One of `cosine`, `euclidean`, or `dot`. | | `recreate_type` | bool | `False` | Whether to drop and recreate the document type on initialization. | | `create_database` | bool | `True` | Whether to create the database if it doesn't exist. | ## Related Information - [ArcadeDBEmbeddingRetriever](/docs/reference/pipeline-components/integrations/arcadedb/ArcadeDBEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ArcadeDBEmbeddingRetriever Retrieve documents from an `ArcadeDBDocumentStore` using vector similarity search. Use this component in query pipelines to find semantically similar documents based on dense embeddings. ## Key Features - Performs vector similarity search against documents stored in ArcadeDB. - Supports cosine, Euclidean, and dot product similarity functions defined on the document store. - Configurable filter policy to merge or replace filters at query time. ## Configuration 1. First, configure an `ArcadeDBDocumentStore` in your pipeline. 2. Drag the `ArcadeDBEmbeddingRetriever` component onto the canvas from the Component Library. 3. Connect an embedder component to provide `query_embedding` as input. 4. Connect the retriever output to downstream components such as `PromptBuilder`. ## Connections `ArcadeDBEmbeddingRetriever` receives a `query_embedding` (list of floats) from a text embedder such as `SentenceTransformersTextEmbedder`. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/arcadedb/src/haystack_integrations/components/retrievers/arcadedb/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ArcadeDBEmbeddingRetriever: type: haystack_integrations.components.retrievers.arcadedb.embedding_retriever.ArcadeDBEmbeddingRetriever init_parameters: document_store: ArcadeDBDocumentStore top_k: 5 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 document_store: type: haystack_integrations.document_stores.arcadedb.document_store.ArcadeDBDocumentStore init_parameters: url: http://localhost:2480 database: my_haystack_db embedding_dimension: 384 retriever: type: haystack_integrations.components.retrievers.arcadedb.embedding_retriever.ArcadeDBEmbeddingRetriever init_parameters: document_store: document_store top_k: 5 connections: - sender: text_embedder.embedding receiver: retriever.query_embedding inputs: query: - text_embedder.text outputs: documents: retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The query embedding vector to search for similar documents. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of the most similar documents from the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | ArcadeDBDocumentStore | | The ArcadeDB document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding vector to search with. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | ## Related Information - [ArcadeDBDocumentStore](/docs/reference/pipeline-components/integrations/arcadedb/ArcadeDBDocumentStore.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AstraDocumentStore Store and retrieve documents using [DataStax Astra DB](https://www.datastax.com/products/datastax-astra), a serverless vector database built on Apache Cassandra. ## Key Features - Stores documents in Astra DB with native vector search support. - Serverless architecture that scales automatically with usage. - Supports cosine, dot product, and Euclidean similarity functions. - Supports namespace isolation for multi-tenant use cases. - Configurable duplicate handling policies. ## Configuration 1. Create an Astra DB instance and obtain your API endpoint and application token from the [Astra DB console](https://astra.datastax.com/). 2. Create secrets with your Astra credentials. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx): - `ASTRA_DB_API_ENDPOINT`: Your Astra DB API endpoint. - `ASTRA_DB_APPLICATION_TOKEN`: Your Astra DB application token. 3. Configure the `AstraDocumentStore` in your pipeline YAML. ## Source Code To check this component's source code, open [`document_store.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/astra/src/haystack_integrations/document_stores/astra/document_store.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AstraDocumentStore: type: haystack_integrations.document_stores.astra.document_store.AstraDocumentStore init_parameters: api_endpoint: type: env_var env_vars: - ASTRA_DB_API_ENDPOINT strict: true token: type: env_var env_vars: - ASTRA_DB_APPLICATION_TOKEN strict: true collection_name: haystack_docs embedding_dimension: 768 similarity: cosine ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_endpoint` | Secret | `Secret.from_env_var("ASTRA_DB_API_ENDPOINT")` | The Astra DB API endpoint URL. | | `token` | Secret | `Secret.from_env_var("ASTRA_DB_APPLICATION_TOKEN")` | The Astra DB application token. | | `collection_name` | str | `documents` | The name of the Astra DB collection to store documents in. | | `embedding_dimension` | int | `768` | The dimensionality of document embeddings. Must match your embedding model's output. | | `duplicates_policy` | DuplicatePolicy | `DuplicatePolicy.NONE` | How to handle duplicate documents. One of `NONE`, `SKIP`, `OVERWRITE`, or `FAIL`. | | `similarity` | str | `cosine` | The vector similarity metric. One of `cosine`, `dot_product`, or `euclidean`. | | `namespace` | Optional[str] | None | The Astra DB namespace (keyspace) to use. | ## Related Information - [AstraEmbeddingRetriever](/docs/reference/pipeline-components/integrations/astra/AstraEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AstraEmbeddingRetriever Retrieve documents from an `AstraDocumentStore` using vector similarity search. Use this component in query pipelines to find semantically similar documents based on dense embeddings stored in DataStax Astra DB. ## Key Features - Performs vector similarity search against documents stored in Astra DB. - Supports cosine, dot product, and Euclidean similarity functions defined on the document store. - Configurable filter policy to merge or replace filters at query time. - Supports async execution via `run_async`. ## Configuration 1. First, configure an `AstraDocumentStore` in your pipeline. 2. Drag the `AstraEmbeddingRetriever` component onto the canvas from the Component Library. 3. Connect an embedder component to provide `query_embedding` as input. 4. Connect the retriever output to downstream components such as `PromptBuilder`. ## Connections `AstraEmbeddingRetriever` receives a `query_embedding` (list of floats) from a text embedder such as `SentenceTransformersTextEmbedder`. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/astra/src/haystack_integrations/components/retrievers/astra/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AstraEmbeddingRetriever: type: haystack_integrations.components.retrievers.astra.retriever.AstraEmbeddingRetriever init_parameters: document_store: AstraDocumentStore top_k: 5 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 document_store: type: haystack_integrations.document_stores.astra.document_store.AstraDocumentStore init_parameters: api_endpoint: type: env_var env_vars: - ASTRA_DB_API_ENDPOINT strict: true token: type: env_var env_vars: - ASTRA_DB_APPLICATION_TOKEN strict: true collection_name: haystack_docs embedding_dimension: 384 retriever: type: haystack_integrations.components.retrievers.astra.retriever.AstraEmbeddingRetriever init_parameters: document_store: document_store top_k: 5 connections: - sender: text_embedder.embedding receiver: retriever.query_embedding inputs: query: - text_embedder.text outputs: documents: retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The query embedding vector to search for similar documents. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of the most similar documents from the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AstraDocumentStore | | The Astra document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding vector to search with. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | ## Related Information - [AstraDocumentStore](/docs/reference/pipeline-components/integrations/astra/AstraDocumentStore.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AmazonBedrockChatGenerator Generate chat responses using large language models hosted on [Amazon Bedrock](https://aws.amazon.com/bedrock/) via the Bedrock Converse API. Bedrock provides access to foundation models from Anthropic, Meta, Mistral, Amazon, and others through a unified API. ## Key Features - Access to models from multiple providers through Amazon Bedrock's Converse API. - Supports Claude, Llama, Mistral, Amazon Titan, and other foundation models. - Supports global inference profiles for automatic cross-region routing (for example, `global.anthropic.claude-sonnet-4-6`). - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports AWS Bedrock Guardrails for content safety. - Supports prompt caching via `tools_cachepoint_config` and `system_cachepoint_config`. - Flexible AWS authentication: access keys, session tokens, IAM roles, or named profiles. ## Configuration 1. Drag the `AmazonBedrockChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Bedrock model you want to use (for example, `global.anthropic.claude-sonnet-4-6` for Claude Sonnet via global inference, or `amazon.nova-pro-v1:0` for Amazon Nova Pro). For available models, see the [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html). 2. Create secrets with your AWS credentials. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Use these environment variable names: - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` - `AWS_DEFAULT_REGION` (required for region-specific models without global inference profiles) 4. Go to the **Advanced** tab to configure `generation_kwargs` such as `maxTokens`, `temperature`, and `topP`. ## Connections `AmazonBedrockChatGenerator` receives a list of `ChatMessage` objects as input, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/generators/amazon_bedrock/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockChatGenerator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: global.anthropic.claude-sonnet-4-6 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false generation_kwargs: maxTokens: 1024 temperature: 0.7 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: system content: You are a helpful assistant. Answer questions based on the provided documents. - role: user content: | Documents: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: global.anthropic.claude-sonnet-4-6 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false generation_kwargs: maxTokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question documents: - prompt_builder.documents outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | | The Amazon Bedrock model ID or cross-region inference profile (for example, `global.anthropic.claude-sonnet-4-6`). For a full list, see the [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html). | | `aws_access_key_id` | Optional[Secret] | `Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False)` | The AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | `Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False)` | The AWS secret access key. | | `aws_session_token` | Optional[Secret] | `Secret.from_env_var("AWS_SESSION_TOKEN", strict=False)` | The AWS session token for temporary credentials. | | `aws_region_name` | Optional[Secret or str] | `Secret.from_env_var("AWS_DEFAULT_REGION", strict=False)` | The AWS region. Required for region-specific models; not needed for global inference profiles. | | `aws_profile_name` | Optional[Secret] | `Secret.from_env_var("AWS_PROFILE", strict=False)` | The AWS named profile to use for authentication. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters passed to Bedrock, such as `maxTokens`, `temperature`, `topP`, and `stopSequences`. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. When set, the model streams tokens as they're generated. | | `boto3_config` | Optional[Dict[str, Any]] | None | Additional configuration for the boto3 client (for example, timeouts). | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use. | | `guardrail_config` | Optional[Dict[str, str]] | None | Configuration for Amazon Bedrock Guardrails content filtering. | | `tools_cachepoint_config` | Optional[Dict[str, str]] | None | Prompt caching configuration for the tools block. | | `system_cachepoint_config` | Optional[Dict[str, str]] | None | Prompt caching configuration for the system prompt block. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model, overriding init-time tools. | ## Related Information - [AmazonBedrockTextEmbedder](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockTextEmbedder.mdx) - [AmazonBedrockDocumentEmbedder](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockDocumentEmbedder.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AmazonBedrockDocumentEmbedder Calculate document embeddings using models through the Amazon Bedrock API. :::info Batch Computing Only Cohere models support computing embeddings for more documents with the same request. ::: ## Key Features - Computes vector embeddings for documents using Amazon Bedrock models. - Supports multiple embedding models, including Amazon Titan and Cohere. - Can embed document metadata alongside document text to improve retrieval quality. - Supports batch processing for Cohere models. - Stores embeddings in the `embedding` field of each `Document` object. - Use `AmazonBedrockDocumentEmbedder` to embed documents in indexes. To embed a query string, use `AmazonBedrockTextEmbedder` instead. ## Configuration ## Configuration :::tip Authentication To use this component, connect with Amazon Bedrock first. You'll need the region name, access key ID, and secret access key. ::: 1. Drag the `AmazonBedrockDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the embedding model from the list. 4. Go to the **Advanced** tab to configure additional settings, such as `batch_size`, `progress_bar`, `meta_fields_to_embed`, `embedding_separator`, and `boto3_config`. ### Embedding Document Metadata You can embed documents' metadata along with the document text. This is useful if the metadata is semantically meaningful and embedding it can improve retrieval. To do this, list the fields to embed in the `meta_fields_to_embed` parameter: ## Connections `AmazonBedrockDocumentEmbedder` receives a list of documents to embed. Connect a preprocessor like `DocumentSplitter` to its `documents` input. It outputs the same documents with the `embedding` field populated. Connect its `documents` output to `DocumentWriter` to write the embedded documents into the document store. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/embedders/amazon_bedrock/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockDocumentEmbedder: type: haystack_integrations.components.embedders.amazon_bedrock.document_embedder.AmazonBedrockDocumentEmbedder init_parameters: model: amazon.titan-embed-text-v1 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false batch_size: 32 progress_bar: true meta_fields_to_embed: - title: travelling_in_africa - type: guide embedding_separator: \n ``` ### Using the Component in an Index This is an example of a standard English index where `AmazonBedrockDocumentEmbedder` receives the documents from `DocumentJoiner` and sends them to `DocumentWriter`. It also has a list of metadata fields to embed: ```yaml # haystack-pipeline # If you need help with the YAML format, have a look at https://docs.cloud.deepset.ai/v2.0/docs/create-a-pipeline#create-a-pipeline-using-pipeline-editor. # This section defines components that you want to use in your pipelines. Each component must have a name and a type. You can also set the component's parameters here. # The name is up to you, you can give your component a friendly name. You then use components' names when specifying the connections in the pipeline. # Type is the class path of the component. You can check the type on the component's documentation page. components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE AmazonBedrockDocumentEmbedder: type: haystack_integrations.components.embedders.amazon_bedrock.document_embedder.AmazonBedrockDocumentEmbedder init_parameters: model: amazon.titan-embed-text-v1 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false batch_size: 32 progress_bar: true meta_fields_to_embed: - title: travelling_in_africa - type: guide embedding_separator: \n boto3_config: connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: splitter.documents receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: AmazonBedrockDocumentEmbedder.documents - sender: AmazonBedrockDocumentEmbedder.documents receiver: writer.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :------------ | :-------------------- | | `documents` | List[Document] | The documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :---------------------------------------------------------------------------- | | `documents` | List[Document] | The documents with the `embedding` field populated with the calculated embedding. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------------|--------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Literal['amazon.titan-embed-text-v1', 'cohere.embed-english-v3', 'cohere.embed-multilingual-v3', 'amazon.titan-embed-text-v2:0']| |The embedding model to use. Choose the model from the list on the component card.| |aws_access_key_id |Optional[Secret] |Secret.from_env_var('AWS_ACCESS_KEY_ID', strict=False) |AWS access key ID. Connect to Amazon Bedrock on the Integrations page. | |aws_secret_access_key|Optional[Secret] |Secret.from_env_var('AWS_SECRET_ACCESS_KEY', strict=False)|AWS secret access key. Connect to Amazon Bedrock on the Integrations page. | |aws_session_token |Optional[Secret] |Secret.from_env_var('AWS_SESSION_TOKEN', strict=False) |AWS session token. Connect to Amazon Bedrock on the Integrations page. | |aws_region_name |Optional[Secret] |Secret.from_env_var('AWS_DEFAULT_REGION', strict=False) |AWS region name. Connect to Amazon Bedrock on the Integrations page. | |aws_profile_name |Optional[Secret] |Secret.from_env_var('AWS_PROFILE', strict=False) |AWS profile name. Connect to Amazon Bedrock on the Integrations page. | |batch_size |int |32 |Number of documents to embed at once. Only Cohere models support batch inference. This parameter is ignored for Amazon Titan models. | |progress_bar |bool |True |Shows a progress bar or not. We recommend disabling it in production deployments to keep the logs clean. | |meta_fields_to_embed |Optional[List[str]] |None |List of metadata fields to embed along with the document text. | |embedding_separator |str |\n |Separator used to concatenate the metadata fields to the document text. | |boto3_config |Optional[Dict[str, Any]] |None |The configuration for the boto3 client. | |kwargs |Any | |Additional parameters to pass for model inference. For example, `input_type` and `truncate` for Cohere models. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :-------------------- | | `documents` | List[Document] | The documents to embed. | ## Related Information - [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) - [AmazonBedrockTextEmbedder](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockTextEmbedder.mdx) --- ## AmazonBedrockDocumentImageEmbedder Compute document embeddings from images using Amazon Bedrock models. Use this component in indexes to create embeddings from images referenced in documents, enabling multimodal semantic search. ## Key Features - Computes vector embeddings from images referenced in documents. - Useful for building multimodal search applications where you want to find documents based on image similarity. - Stores embeddings in the `embedding` field of each `Document` object. - Supports optional image resizing to fit within specified dimensions while maintaining aspect ratio. - Supports the following models: `amazon.titan-embed-image-v1`, `cohere.embed-english-v3`, and `cohere.embed-multilingual-v3`. ## Configuration To use this component, connect to your AWS account by adding secrets with the following keys: - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` - `AWS_DEFAULT_REGION` For details on how to create secrets, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). For instructions on using Bedrock models, see [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx). ::: 1. Drag the `AmazonBedrockDocumentImageEmbedder` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Select the embedding model from the list. 4. Go to the **Advanced** tab to configure the AWS credentials, file path metadata field, root path, image size, progress bar, and boto3 client settings. ## Connections `AmazonBedrockDocumentImageEmbedder` accepts a list of documents with image file paths in their metadata as input. It outputs a list of documents with embeddings stored in the `embedding` field. Connect a converter like `ImageFileToDocument` to the `documents` input to provide image documents for embedding. Connect the `documents` output to `DocumentWriter` to store the embedded documents in the document store. 1. Drag the `AmazonBedrockDocumentImageEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the embedding model from the list. - Set the `file_path_meta_field` to the metadata field in your documents that contains the image file path. 4. Go to the **Advanced** tab to configure additional settings, such as `root_path`, `image_size`, `progress_bar`, and `boto3_config`. ## Source Code To check this component's source code, open [`document_image_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/embedders/amazon_bedrock/document_image_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `AmazonBedrockDocumentImageEmbedder` receives documents that contain image file paths in their metadata. Connect a converter like `ImageFileToDocument` to its `documents` input. It outputs the same documents with the `embedding` field populated. Connect its `documents` output to `DocumentWriter` to write the embedded documents into the document store. ## Usage Examples ### Basic Configuration ```yaml image_embedder: type: haystack_integrations.components.embedders.amazon_bedrock.document_image_embedder.AmazonBedrockDocumentImageEmbedder init_parameters: model: amazon.titan-embed-image-v1 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false file_path_meta_field: file_path progress_bar: true ``` This is an example indexing pipeline with `AmazonBedrockDocumentImageEmbedder` for image-based document embedding: ```yaml # haystack-pipeline components: converter: type: haystack.components.converters.image.file_to_document.ImageFileToDocument init_parameters: {} image_embedder: type: haystack_integrations.components.embedders.amazon_bedrock.document_image_embedder.AmazonBedrockDocumentImageEmbedder init_parameters: model: amazon.titan-embed-image-v1 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false file_path_meta_field: file_path root_path: image_size: progress_bar: true boto3_config: writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'images' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: converter.documents receiver: image_embedder.documents - sender: image_embedder.documents receiver: writer.documents max_runs_per_component: 100 metadata: {} inputs: files: - converter.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :------------ | :-------------------------------------------------------- | | `documents` | List[Document] | A list of documents with image file paths in their metadata. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :--------------------------------------------------- | | `documents` | List[Document] | Documents with embeddings stored in the `embedding` field. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | Literal['amazon.titan-embed-image-v1', 'cohere.embed-english-v3', 'cohere.embed-multilingual-v3'] | | The Bedrock model to use for calculating embeddings. | | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var('AWS_ACCESS_KEY_ID') | AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var('AWS_SECRET_ACCESS_KEY') | AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var('AWS_SESSION_TOKEN') | AWS session token for temporary credentials. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var('AWS_DEFAULT_REGION') | AWS region name. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var('AWS_PROFILE') | AWS profile name. | | `file_path_meta_field` | str | "file_path" | The metadata field in the Document that contains the file path to the image. | | `root_path` | Optional[str] | None | The root directory path where document files are located. If provided, file paths in document metadata are resolved relative to this path. | | `image_size` | Optional[Tuple[int, int]] | None | If provided, resizes the image to fit within the specified dimensions (width, height) while maintaining aspect ratio. | | `progress_bar` | bool | True | If `True`, shows a progress bar when embedding documents. | | `boto3_config` | Optional[Dict[str, Any]] | None | Configuration for the boto3 client. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :-------------------------------------------------------- | | `documents` | List[Document] | A list of documents with image file paths in their metadata. | ## Related Information - [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## AmazonBedrockRanker Rank documents based on their similarity to the query using models hosted on Amazon Bedrock. ## Key Features - Ranks documents by semantic similarity to the query. - Returns documents in descending order of relevance score. - Supports the following ranking models: `cohere.rerank-v3-5:0` and `amazon.rerank-v1:0`. - Lets you limit the number of returned documents with `top_k`. - Can embed document metadata alongside document content for richer ranking. ## Configuration To use this component, connect with Amazon Bedrock first. You'll need: - The region name - Access key ID - Secret access key ::: 1. Drag the `AmazonBedrockRanker` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Select the ranking model from the list. 4. Go to the **Advanced** tab to configure the AWS credentials, number of top results, maximum chunks per document, metadata fields to embed, and metadata separator. ## Connections `AmazonBedrockRanker` accepts a query string, a list of documents to rank, and an optional `top_k` value as inputs. It outputs a list of documents sorted by relevance to the query. Connect a retriever's `documents` output to the `documents` input. Connect the pipeline's query input to the `query` input. Connect the `documents` output to `PromptBuilder` or another component that processes ranked documents. 1. Drag the `AmazonBedrockRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the ranking model. - Set `top_k` to limit the number of documents to return. 4. Go to the **Advanced** tab to configure additional settings, such as `max_chunks_per_doc`, `meta_fields_to_embed`, and `meta_data_separator`. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/rankers/amazon_bedrock/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `AmazonBedrockRanker` receives a query string and a list of documents to rank. Connect a retriever's `documents` output to its `documents` input, and connect the pipeline `query` input to its `query` input. It outputs the ranked documents in descending order of relevance. Connect its `documents` output to a prompt builder or directly to the pipeline output. ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockRanker: type: haystack_integrations.components.rankers.amazon_bedrock.ranker.AmazonBedrockRanker init_parameters: model: cohere.rerank-v3-5:0 top_k: 10 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false meta_data_separator: \n ``` ### Using the Component in a Pipeline This is an example of a document search pipeline that uses AmazonBedrockRanker with the cohere ranking model: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate AmazonBedrockRanker: type: haystack_integrations.components.rankers.amazon_bedrock.ranker.AmazonBedrockRanker init_parameters: model: cohere.rerank-v3-5:0 top_k: 10 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false max_chunks_per_doc: meta_fields_to_embed: meta_data_separator: \n connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: AmazonBedrockRanker.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "AmazonBedrockRanker.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "AmazonBedrockRanker.documents" # The output of the pipeline is the retrieved documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :------------ | :------ | :----------------------------------------------------------- | | `query` | str | | The query used for ranking documents by their similarity to the query. | | `documents` | List[Document] | | The documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents you want the Ranker to return. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :---------------------------------------------------------------------------- | | `documents` | List[Document] | Documents most similar to the query in descending order of similarity. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | cohere.rerank-v3-5:0 | The ranking model to use. | | `top_k` | int | 10 | The maximum number of documents to return. | | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var(["AWS_ACCESS_KEY_ID"], strict=False) | AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var(["AWS_SECRET_ACCESS_KEY"], strict=False) | AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var([AWS_SESSION_TOKEN], strict=False) | AWS session token. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var(["AWS_DEFAULT_REGION"], strict=False) | AWS region name. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var(["AWS_PROFILE"], strict=False) | AWS profile name. | | `max_chunks_per_doc` | Optional[int] | None | If your document exceeds 512 tokens, this setting determines the maximum number of chunks a document can be split into. If set to None, uses the default of 10 chunks. This parameter is not used currently but it's included for future compatibility. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of metadata fields to embed in the document content. | | `meta_data_separator` | str | \n | The separator used to concatenate the metadata fields to the document content. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :------------ | :------ | :----------------------------------------------------------- | | `query` | str | | The user query for ranking the documents. | | `documents` | List[Document] | | The documents to rank. | | `top_k` | Optional[int] | None | The maximum number of documents you want the Ranker to return. | ## Related Information - [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AmazonBedrockTextEmbedder Calculate text embeddings using models through the Amazon Bedrock API. ## Key Features - Computes vector embeddings for text strings, such as user queries, using Amazon Bedrock models. - Supports multiple embedding models, including Amazon Titan and Cohere. - Use `AmazonBedrockTextEmbedder` to embed query strings. To embed documents, use `AmazonBedrockDocumentEmbedder` instead. ## Configuration ## Configuration :::tip Authentication To use this component, connect with Amazon Bedrock first. You'll need the region name, access key ID, and secret access key. ::: 1. Drag the `AmazonBedrockTextEmbedder` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Select the embedding model from the list. Make sure to use the same model that was used to embed documents in the index. 4. Go to the **Advanced** tab to configure the AWS credentials and boto3 client settings. ## Connections `AmazonBedrockTextEmbedder` accepts a text string as input and outputs a list of floats representing the text embedding. Connect the pipeline's query input to the `text` input. Connect the `embedding` output to an embedding retriever's `query_embedding` input to find matching documents. 1. Drag the `AmazonBedrockTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the embedding model from the list. 4. Go to the **Advanced** tab to configure additional settings, such as `boto3_config` and additional model inference parameters. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/embedders/amazon_bedrock/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `AmazonBedrockTextEmbedder` receives a text string to embed. Connect the `query` output of the `Input` component to its `text` input. It outputs a list of floats representing the embedding. Connect its `embedding` output to an embedding retriever's `query_embedding` input. ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockTextEmbedder: type: haystack_integrations.components.embedders.amazon_bedrock.text_embedder.AmazonBedrockTextEmbedder init_parameters: model: cohere.embed-english-v3 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false ``` ### Using the Component in a Pipeline This is an example of a basic document search pipeline where `AmazonBedrockTextEmbedder` uses a Cohere model to embed the query and send the resulting embedding to an Embedding Retriever: ```yaml # haystack-pipeline components: OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine index: Standard-Index-English max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: false AmazonBedrockTextEmbedder: type: haystack_integrations.components.embedders.amazon_bedrock.text_embedder.AmazonBedrockTextEmbedder init_parameters: model: cohere.embed-english-v3 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: connections: - sender: AmazonBedrockTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - AmazonBedrockTextEmbedder.text outputs: documents: OpenSearchEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :---------- | :------------------------------ | | `embedding` | List[float] | The embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------------|--------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Literal['amazon.titan-embed-text-v1', 'cohere.embed-english-v3', 'cohere.embed-multilingual-v3', 'amazon.titan-embed-text-v2:0']| |The embedding model to use. The model has to be specified in the format outlined in the Amazon Bedrock [documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html). Make sure the embedding model used for embedding the query is the same as the embedding model used to embed documents in the index.| |aws_access_key_id |Optional[Secret] |Secret.from_env_var('AWS_ACCESS_KEY_ID', strict=False) |AWS access key ID. | |aws_secret_access_key|Optional[Secret] |Secret.from_env_var('AWS_SECRET_ACCESS_KEY', strict=False)|AWS secret access key. | |aws_session_token |Optional[Secret] |Secret.from_env_var('AWS_SESSION_TOKEN', strict=False) |AWS session token. | |aws_region_name |Optional[Secret] |Secret.from_env_var('AWS_DEFAULT_REGION', strict=False) |AWS region name. | |aws_profile_name |Optional[Secret] |Secret.from_env_var('AWS_PROFILE', strict=False) |AWS profile name. | |boto3_config |Optional[Dict[str, Any]] |None |The configuration for the boto3 client. | |kwargs |Any | |Additional parameters to pass for model inference. For example, `input_type` and `truncate` for Cohere models. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :--------------------- | | `text` | str | The input text to embed. | ## Related Information - [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) - [AmazonBedrockDocumentEmbedder](/docs/reference/pipeline-components/integrations/aws/AmazonBedrockDocumentEmbedder.mdx) --- ## AmazonTextractConverter Convert images and single-page PDFs to Haystack Documents using AWS Textract for OCR and structured data extraction. ## Key Features - Extracts text from images (JPEG, PNG, TIFF, BMP) and single-page PDFs using AWS Textract. - Supports plain text OCR as well as structured data extraction (tables, forms, layouts). - Supports natural language queries to extract specific information from documents. - Automatically adds `QUERIES` feature type when queries are provided at runtime. - Returns both Haystack Documents and raw Textract API responses. - AWS credentials are resolved through AWS Secret parameters or the standard boto3 credential chain. ## Configuration 1. Drag the `AmazonTextractConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create secrets for your AWS credentials. Use `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` as the environment variable names. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally set `feature_types` to enable table extraction (`TABLES`), form extraction (`FORMS`), layout analysis (`LAYOUT`), or signature detection (`SIGNATURES`). 4. Go to the **Advanced** tab to configure `store_full_path` and `boto3_config`. ## Connections `AmazonTextractConverter` receives a list of file sources (paths or `ByteStream` objects). It outputs a list of `Document` objects containing the extracted text and a list of raw Textract API responses. ## Source Code To check this component's source code, open [`converter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_textract/src/haystack_integrations/components/converters/amazon_textract/converter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AmazonTextractConverter: type: haystack_integrations.components.converters.amazon_textract.AmazonTextractConverter init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false feature_types: ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: AmazonTextractConverter: type: haystack_integrations.components.converters.amazon_textract.AmazonTextractConverter init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false feature_types: - TABLES - FORMS document_splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 connections: - sender: AmazonTextractConverter.documents receiver: document_splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths, `Path` objects, or `ByteStream` objects to convert. Supported formats are JPEG, PNG, TIFF, BMP, and single-page PDF files (up to 10 MB). | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Metadata to add to all documents, or a list of metadata dicts (one per source). | | `queries` | Optional[List[str]] | A list of natural language queries to extract specific information from documents. Automatically enables the `QUERIES` Textract feature. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The extracted text as Haystack Documents. | | `raw_textract_response` | List[Dict] | The raw API responses from AWS Textract for each input file. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `aws_access_key_id` | Optional[Secret] | `Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False)` | The AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | `Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False)` | The AWS secret access key. | | `aws_session_token` | Optional[Secret] | `Secret.from_env_var("AWS_SESSION_TOKEN", strict=False)` | The AWS session token for temporary credentials. | | `aws_region_name` | Optional[Secret] | `Secret.from_env_var("AWS_DEFAULT_REGION", strict=False)` | The AWS region to use (for example, `us-east-1`). | | `aws_profile_name` | Optional[Secret] | `Secret.from_env_var("AWS_PROFILE", strict=False)` | The AWS named profile to use. | | `feature_types` | Optional[List[str]] | None | Textract feature types to enable. Options are `TABLES`, `FORMS`, `SIGNATURES`, and `LAYOUT`. When not set, uses basic text detection only. The `QUERIES` type is added automatically when queries are provided at runtime. | | `store_full_path` | bool | False | Whether to store the full file path in document metadata, or just the filename. | | `boto3_config` | Optional[Dict[str, Any]] | None | A dictionary of additional configuration options for the boto3 Textract client. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of file paths or streams to convert. | | `meta` | Optional[Union[Dict, List[Dict]]] | None | Metadata to add to the resulting documents. | | `queries` | Optional[List[str]] | None | Natural language queries to extract specific information. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## S3Downloader Download files from AWS S3 buckets to the local filesystem. Use this component in indexes when your documents reference files stored in S3 that need to be processed locally. ## Key Features - Downloads files from Amazon S3 buckets for use in pipeline processing. - Supports concurrent downloads for improved performance. - Filters downloads by file extension to reduce unnecessary processing. - Caches downloaded files to avoid redundant downloads. - Supports custom S3 key generation functions if your S3 file structure doesn't match your document metadata. ## Configuration To use this component, connect with your AWS account. Create secrets with the following keys: - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` - `AWS_DEFAULT_REGION` For details on how to create secrets, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 1. Drag the `S3Downloader` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `file_extensions` to specify which file types to download. For example, `[".pdf", ".txt"]`. - Set `file_name_meta_key` to the metadata field in your documents that contains the S3 file name. - Optionally, set `file_root_path` to the local directory where files will be downloaded. 4. Go to the **Advanced** tab to configure additional settings, such as `max_workers`, `max_cache_size`, `s3_key_generation_function`, and `boto3_config`. ### File Extension Filtering You can use the `file_extensions` parameter to download only specific file types, reducing unnecessary downloads and processing time. For example, `file_extensions=[".pdf", ".txt"]` downloads only PDF and TXT files while skipping others. ### Custom S3 Key Generation By default, the component uses the `file_name` from Document metadata as the S3 key. If your S3 file structure doesn't match the file names in metadata, you can provide an optional `s3_key_generation_function` to customize how S3 keys are generated from Document metadata. ## Connections `S3Downloader` receives documents that contain S3 file references in their metadata. Connect a converter's `documents` output to its `documents` input. It outputs the same documents with the `file_path` metadata updated to point to the downloaded local files. Connect its `documents` output to a document cleaner, splitter, or other preprocessor. ## Source Code To check this component's source code, open [`s3_downloader.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/downloaders/s3/s3_downloader.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml s3_downloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false file_extensions: - .pdf - .txt - .docx - .html file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key ``` This is an example indexing pipeline with `S3Downloader` to download and process files from S3: ```yaml # haystack-pipeline components: s3_downloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: file_root_path: file_extensions: - .pdf - .txt - .docx - .html file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key converter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 cleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false keep_id: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 split_threshold: 0 document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 normalize_embeddings: true writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: cleaner.documents receiver: splitter.documents - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents - sender: converter.documents receiver: s3_downloader.documents - sender: s3_downloader.documents receiver: cleaner.documents max_runs_per_component: 100 metadata: {} inputs: files: - converter.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :------------ | :-------------------------------------------------------- | | `documents` | List[Document] | A list of documents with S3 file references in their metadata. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :---------------------------------------------------------------------------------------------- | | `documents` | List[Document] | Documents with the `file_path` metadata updated to point to the downloaded local files. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var('AWS_ACCESS_KEY_ID') | AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var('AWS_SECRET_ACCESS_KEY') | AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var('AWS_SESSION_TOKEN') | AWS session token for temporary credentials. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var('AWS_DEFAULT_REGION') | AWS region name. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var('AWS_PROFILE') | AWS profile name. | | `boto3_config` | Optional[Dict[str, Any]] | None | Configuration for the boto3 client. | | `file_root_path` | Optional[str] | None | The path where files are downloaded. Can be set through this parameter or the `FILE_ROOT_PATH` environment variable. If the specified directory doesn't exist, it's created. | | `file_extensions` | Optional[List[str]] | None | File extensions permitted for download. By default, all file extensions are allowed. | | `file_name_meta_key` | str | "file_name" | The metadata key that contains the file name to download. | | `max_workers` | int | 32 | Maximum number of workers for concurrent downloads. | | `max_cache_size` | int | 100 | Maximum number of files to cache. | | `s3_key_generation_function` | Optional[Callable] | None | A function to generate S3 keys from documents. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :-------------------------------------------------------- | | `documents` | List[Document] | A list of documents with S3 file references in their metadata. | ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Use Amazon Bedrock and SageMaker Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) --- ## SagemakerGenerator Generate text using large language models deployed on Amazon SageMaker Inference Endpoints. ## Key Features - Works with any LLM deployed on an Amazon SageMaker Inference Endpoint. - Supports SageMaker JumpStart foundation models including Llama, Falcon, and others. - Accepts a text prompt and returns generated text responses. - AWS credentials are resolved through Secret parameters or the standard boto3 credential chain. - Configurable generation parameters through `generation_kwargs`. ## Configuration 1. Drag the `SagemakerGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the name of your SageMaker Inference Endpoint. 2. Create secrets for your AWS credentials. Use `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_DEFAULT_REGION` as the environment variable names. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs` (for example, `max_new_tokens`) and `aws_custom_attributes`. ## Connections `SagemakerGenerator` receives a text prompt string. It outputs a list of text replies and associated metadata. ## Source Code To check this component's source code, open [`sagemaker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_sagemaker/src/haystack_integrations/components/generators/amazon_sagemaker/sagemaker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml SagemakerGenerator: type: haystack_integrations.components.generators.amazon_sagemaker.SagemakerGenerator init_parameters: model: my-sagemaker-endpoint-name aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false generation_kwargs: max_new_tokens: 1024 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: "Answer this question: {{ question }}" llm: type: haystack_integrations.components.generators.amazon_sagemaker.SagemakerGenerator init_parameters: model: my-sagemaker-endpoint-name aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false generation_kwargs: max_new_tokens: 512 connections: - sender: prompt_builder.prompt receiver: llm.prompt max_runs_per_component: 100 metadata: {} inputs: query: - prompt_builder.question ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `prompt` | str | The text prompt to send to the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | Generation parameters to override init-time values. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[str] | A list of generated text responses. | | `meta` | List[Dict[str, Any]] | Metadata about each generation response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The name of the SageMaker Inference Endpoint to call. | | `aws_access_key_id` | Optional[Secret] | `Secret.from_env_var("AWS_ACCESS_KEY_ID", strict=False)` | The AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | `Secret.from_env_var("AWS_SECRET_ACCESS_KEY", strict=False)` | The AWS secret access key. | | `aws_session_token` | Optional[Secret] | `Secret.from_env_var("AWS_SESSION_TOKEN", strict=False)` | The AWS session token for temporary credentials. | | `aws_region_name` | Optional[Secret] | `Secret.from_env_var("AWS_DEFAULT_REGION", strict=False)` | The AWS region where the endpoint is deployed. | | `aws_profile_name` | Optional[Secret] | `Secret.from_env_var("AWS_PROFILE", strict=False)` | The AWS named profile to use. | | `aws_custom_attributes` | Optional[Dict[str, Any]] | None | Custom attributes to pass to the SageMaker endpoint invocation. | | `generation_kwargs` | Optional[Dict[str, Any]] | `{"max_new_tokens": 1024}` | Default generation parameters sent to the SageMaker endpoint, such as `max_new_tokens`, `temperature`, and `top_p`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `prompt` | str | | The text prompt to send to the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AzureDocumentIntelligenceConverter Convert files to Haystack Documents using [Azure AI Document Intelligence](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/), extracting structured text with tables, headings, and layout. ## Key Features - Converts PDF, JPEG, PNG, BMP, TIFF, DOCX, XLSX, PPTX, and HTML files. - Outputs GitHub Flavored Markdown, preserving document structure for LLM and RAG applications. - Accurately preserves headings, tables (as Markdown tables), lists, and reading order. - Supports multiple Azure Document Intelligence models through the `model_id` parameter. - Returns both Haystack Documents and raw Azure API responses. ## Configuration 1. Drag the `AzureDocumentIntelligenceConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `endpoint` to your Azure Document Intelligence resource endpoint URL. 2. Create a secret with your Azure Document Intelligence API key. Use `AZURE_DI_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `model_id` and `store_full_path`. ## Connections `AzureDocumentIntelligenceConverter` receives a list of file sources. It outputs a list of `Document` objects containing the extracted text and a list of raw Azure API responses. ## Source Code To check this component's source code, open [`converter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/azure_doc_intelligence/src/haystack_integrations/components/converters/azure_doc_intelligence/converter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AzureDocumentIntelligenceConverter: type: haystack_integrations.components.converters.azure_doc_intelligence.converter.AzureDocumentIntelligenceConverter init_parameters: endpoint: https://my-resource.cognitiveservices.azure.com/ api_key: type: env_var env_vars: - AZURE_DI_API_KEY strict: false model_id: prebuilt-document ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: AzureDocumentIntelligenceConverter: type: haystack_integrations.components.converters.azure_doc_intelligence.converter.AzureDocumentIntelligenceConverter init_parameters: endpoint: https://my-resource.cognitiveservices.azure.com/ api_key: type: env_var env_vars: - AZURE_DI_API_KEY strict: false model_id: prebuilt-layout document_splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 connections: - sender: AzureDocumentIntelligenceConverter.documents receiver: document_splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths, `Path` objects, or `ByteStream` objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Metadata to add to all documents, or a list of metadata dicts (one per source). | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The extracted text as Haystack Documents in Markdown format. | | `raw_azure_response` | List[Dict] | The raw API responses from Azure Document Intelligence for each input file. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `endpoint` | str | *(required)* | The endpoint URL of your Azure Document Intelligence resource (for example, `https://my-resource.cognitiveservices.azure.com/`). | | `api_key` | Secret | `Secret.from_env_var("AZURE_DI_API_KEY")` | The API key for your Azure Document Intelligence resource. | | `model_id` | str | `prebuilt-document` | The Azure Document Intelligence model to use. Common values are `prebuilt-document`, `prebuilt-layout`, `prebuilt-read`, and `prebuilt-invoice`. | | `store_full_path` | bool | False | Whether to store the full file path in document metadata, or just the filename. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of file paths or streams to convert. | | `meta` | Optional[Union[Dict, List[Dict]]] | None | Metadata to add to the resulting documents. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AzureOCRDocumentConverter Convert files to documents using Azure's Document Intelligence service. It supports PDF, JPEG, PNG, BMP, TIFF, DOCX, XLSX, PPTX, and HTML file formats. *** ## Key Features - Converts files to Haystack `Document` objects using Azure Document Intelligence OCR. - Supports the following file formats: PDF, JPEG, PNG, BMP, TIFF, DOCX, XLSX, PPTX, and HTML. - Includes table context by capturing lines before and after tables as metadata. - Supports multiple page reading orders: `natural` (Azure-determined) and `single_column`. - Optionally attaches metadata to the output documents. ## Configuration To use this component, you need an active Azure account and a Document Intelligence or Cognitive Services resource. For help with setting up your resource, see [Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api). Connect to your Azure account on the Integrations page. For detailed instructions, see [Use Azure Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx). ::: 1. Drag the `AzureOCRDocumentConverter` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Enter the endpoint of your Azure Document Intelligence resource. 4. Go to the **Advanced** tab to configure the API key, model ID, page layout, context length settings, and other optional parameters. ## Connections `AzureOCRDocumentConverter` accepts a list of file paths or ByteStream objects as input and optional metadata to attach to the documents. It outputs a list of converted documents and the raw Azure API responses. Connect a `FileTypeRouter` to the `sources` input to classify and route files for conversion. Connect the `documents` output to a `DocumentJoiner` to combine documents from all converters in the pipeline. 1. Drag the `AzureOCRDocumentConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the endpoint of your Azure Document Intelligence resource. - Enter your API key, or set it using the `AZURE_AI_API_KEY` environment variable. - Select the model ID for the document analysis model. - Choose the page layout (`natural` or `single_column`). 4. Go to the **Advanced** tab to configure additional settings, such as `preceding_context_len`, `following_context_len`, `merge_multiple_column_headers`, `threshold_y`, and `store_full_path`. ## Source Code To check this component's source code, open [`azure.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/azure.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `AzureOCRDocumentConverter` accepts a list of file paths or `ByteStream` objects as sources. Connect a `FileTypeRouter`'s relevant output to its `sources` input. It outputs a list of converted `Document` objects and the raw Azure responses. Connect its `documents` output to a `DocumentJoiner` or preprocessor. ## Usage Examples ### Basic Configuration ```yaml ocr_converter: type: haystack.components.converters.azure.AzureOCRDocumentConverter init_parameters: api_key: type: env_var env_vars: - AZURE_AI_API_KEY strict: false endpoint: YOUR-ENDPOINT model_id: prebuilt-read page_layout: natural ``` ### Using the Component in an Index This example shows how to use the `AzureOCRDocumentConverter` in an index. It uses a `FileTypeRouter` to classify the files and then uses the `AzureOCRDocumentConverter` to convert the files to documents. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 ocr_converter: type: haystack.components.converters.azure.AzureOCRDocumentConverter init_parameters: api_key: {"type": "env_var", "env_vars": ["AZURE_AI_API_KEY"], "strict": false} endpoint: "YOUR-ENDPOINT" model_id: "prebuilt-read" page_layout: "natural" markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: ocr_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: ocr_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: splitter.documents receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :-------------------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `meta` | Optional[List[Dict[str, Any]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists are zipped. If `sources` contains ByteStream objects, their `meta` is added to the output Documents. | ### Outputs | Parameter | Type | Description | | :----------------- | :------------ | :------------------------------------------------------- | | `documents` | List[Document] | The output documents. | | `raw_azure_response` | List[Dict] | List of raw Azure responses used to create the documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------------------- | :--------------------------------- | :------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint` | str | | The endpoint of your Azure resource. | | `api_key` | Secret | Secret.from_env_var('AZURE_AI_API_KEY') | The API key of your Azure resource. | | `model_id` | str | prebuilt-read | The ID of the model you want to use. For a list of available models, see [Azure documentation](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/choose-model-feature). | | `preceding_context_len` | int | 3 | Number of lines before a table to include as preceding context (this will be added to the metadata). | | `following_context_len` | int | 3 | Number of lines after a table to include as subsequent context (this will be added to the metadata). | | `merge_multiple_column_headers` | bool | True | If `True`, merges multiple column header rows into a single row. | | `page_layout` | Literal['natural', 'single_column'] | natural | The type of reading order to follow. Possible options: `natural` uses the natural reading order determined by Azure. `single_column` groups all lines with the same height on the page based on a threshold determined by `threshold_y`. | | `threshold_y` | Optional[float] | 0.05 | Only relevant if `single_column` is set to `page_layout`. The threshold, in inches, to determine if two recognized PDF elements are grouped into a single line. | | `store_full_path` | bool | False | If True, the full path of the file is stored in the metadata of the document. If False, only the file name is stored. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :-------------------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sources` | List[Union[str, Path, ByteStream]] | | List of file paths or ByteStream objects. | | `meta` | Optional[List[Dict[str, Any]]] | None | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists are zipped. If `sources` contains ByteStream objects, their `meta` is added to the output Documents. | ## Related Information - [Use Azure Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AzureOpenAIChatGenerator Generate text using OpenAI's models on Azure. It works with GPT-4-type models and supports streaming responses. ## Key Features - Generates text using OpenAI GPT-4-type models deployed on Azure OpenAI. - Supports streaming responses token by token. - Supports tool calling with `Tool` objects or a `Toolset`. - Accepts Azure Active Directory (Entra ID) tokens for authentication in addition to API keys. - Customizable generation behavior through `generation_kwargs` (temperature, max_tokens, and others). ## Configuration To use this component, connect with Azure OpenAI first: ::: 1. Drag the `AzureOpenAIChatGenerator` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. You can set the API key, endpoint, deployment name, and other parameters directly or through environment variables (`AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`). ## Connections `AzureOpenAIChatGenerator` accepts a list of `ChatMessage` instances as input, along with optional streaming callback, generation parameters, and tools. It outputs a list of `ChatMessage` responses. Typically, you connect a `ChatPromptBuilder` to the `messages` input to build dynamic prompts. Connect the `replies` output to `DeepsetAnswerBuilder` through an `OutputAdapter` for further processing. 1. Drag the `AzureOpenAIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Azure endpoint and deployment name (model name). - Enter your API key, or set it using the `AZURE_OPENAI_API_KEY` environment variable. - Set `generation_kwargs` to configure model behavior, such as `temperature` and `max_tokens`. 4. Go to the **Advanced** tab to configure additional settings, such as `timeout`, `max_retries`, `organization`, `streaming_callback`, `tools`, `tools_strict`, `http_client_kwargs`, and `default_headers`. ## Source Code To check this component's source code, open [`azure.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/azure.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `AzureOpenAIChatGenerator` receives a list of `ChatMessage` objects. Connect a `ChatPromptBuilder`'s `prompt` output to its `messages` input. It outputs a list of `ChatMessage` objects as `replies`. Connect its `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`, or use it as the pipeline's final output. ## Usage Examples ### Basic Configuration ```yaml AzureOpenAIChatGenerator: type: haystack.components.generators.chat.azure.AzureOpenAIChatGenerator init_parameters: api_version: '2023-05-15' azure_deployment: gpt-4o-mini api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false azure_ad_token: type: env_var env_vars: - AZURE_OPENAI_AD_TOKEN strict: false tools_strict: false ``` This is a RAG pipeline where `AzureOpenAIChatGenerator` sends the generated replies to `DeepsetAnswerBuilder` through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false AzureOpenAIChatGenerator: type: haystack.components.generators.chat.azure.AzureOpenAIChatGenerator init_parameters: azure_endpoint: api_version: '2023-05-15' azure_deployment: gpt-4o-mini api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false azure_ad_token: type: env_var env_vars: - AZURE_OPENAI_AD_TOKEN strict: false organization: streaming_callback: timeout: max_retries: generation_kwargs: default_headers: tools: tools_strict: false azure_ad_token_provider: http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: AzureOpenAIChatGenerator.messages - sender: AzureOpenAIChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the generation endpoint. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of Tool objects or a Toolset that the model can use. Each tool should have a unique name. If set, it will override the `tools` parameter set during component initialization. | | `tools_strict` | Optional[Bool] | None | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the parameters field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter set during component initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :--------------------------- | | `replies` | List[ChatMessage] | The responses from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :---------------------- | :------------------------------------------------------------- | :-------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `azure_endpoint` | Optional[str] | None | The endpoint of the deployed model, for example `"https://example-resource.azure.openai.com/"`. | | `api_version` | Optional[str] | 2024-12-01 | The version of the API to use. Defaults to 2024-12-01. | | `azure_deployment` | Optional[str] | gpt-4.1-mini | The deployment of the model, usually the model name. | | `api_key` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The API key to use for authentication. | | `azure_ad_token` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_AD_TOKEN', strict=False) | [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id). | | `organization` | Optional[str] | None | Your organization ID. For help, see [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) as an argument. | | `timeout` | Optional[float] | None | Timeout for OpenAI client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model. These parameters are sent directly to the OpenAI endpoint. For details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). Some of the supported parameters: `max_tokens` (maximum output tokens), `temperature` (sampling temperature; higher values mean more risk), `top_p` (nucleus sampling probability mass), `n` (completions per prompt), `stop` (stop sequences), `presence_penalty`, `frequency_penalty`, `logit_bias`. | | `default_headers` | Optional[Dict[str, str]] | None | Default headers to use for the AzureOpenAI client. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `tools_strict` | bool | False | Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. | | `azure_ad_token_provider` | Optional[Union[AzureADTokenProvider, AsyncAzureADTokenProvider]] | None | A function that returns an Azure Active Directory token, will be invoked on every request. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters This component has no run method parameters. ## Related Information - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AzureOpenAIDocumentEmbedder Calculate document embeddings using OpenAI models deployed on Azure. ## Key Features - Computes vector embeddings for documents using Azure OpenAI embedding models. - Enables semantic-based document retrieval in index pipelines. - Can embed document metadata alongside document text to improve retrieval quality. - Supports batch processing and shows a progress bar during indexing. - Stores embeddings in the `embedding` field of each `Document` object. ## Configuration - Embeds a list of documents using OpenAI embedding models deployed on Azure. - Supports embedding document metadata along with document text. - Configurable batch size and progress tracking. - Returns token usage metadata alongside embedded documents. - Use `AzureOpenAITextEmbedder` to embed user queries in search pipelines. ## Configuration :::tip Authentication You need an Azure OpenAI API key to use this component. Connect to your Azure OpenAI account. For more information, see [Using Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx). ::: 1. Drag the `AzureOpenAIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. You can set the API key and endpoint through environment variables (`AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`) or directly in the configuration panel. ## Connections `AzureOpenAIDocumentEmbedder` accepts a list of documents as input. It outputs a list of documents with embeddings and metadata about model usage. Connect a preprocessor like `DocumentSplitter` to the `documents` input. Connect the `documents` output to `DocumentWriter` to store the embedded documents in the document store. 1. Drag the `AzureOpenAIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Azure endpoint and deployment name (embedding model name). - Enter your API key, or set it using the `AZURE_OPENAI_API_KEY` environment variable. - Set `batch_size` to control how many documents are embedded at once. 4. Go to the **Advanced** tab to configure additional settings, such as `prefix`, `suffix`, `progress_bar`, `timeout`, `max_retries`, `organization`, `meta_fields_to_embed`, `embedding_separator`, and `http_client_kwargs`. ## Source Code To check this component's source code, open [`azure_document_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/azure_document_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `AzureOpenAIDocumentEmbedder` receives a list of documents to embed. Connect a preprocessor like `DocumentSplitter` to its `documents` input. It outputs the same documents with the `embedding` field populated, along with usage metadata. Connect its `documents` output to `DocumentWriter` to write the embedded documents into the document store. ## Usage Examples ### Basic Configuration ```yaml AzureOpenAIDocumentEmbedder: type: haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder init_parameters: azure_deployment: text-embedding-ada-002 api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false ``` This is a simple index that uses `AzureOpenAIDocumentEmbedder` to embed documents and write them into an OpenSearch document store. ```yaml # haystack-pipeline components: splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 document_embedder: type: haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder init_parameters: azure_deployment: text-embedding-ada-002 api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 1536 index: default policy: OVERWRITE connections: - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents inputs: documents: - splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :---------- | :------------- | :--------------------------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :------------- | :----------------------------------------------------------------------------- | | `documents` | List[Document] | A list of documents with embeddings. | | `meta` | Dict[str, Any] | Information about the usage of the model, including model name and token usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :---------------------- | :---------------------------- | :-------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `azure_endpoint` | Optional[str] | None | The endpoint of the model deployed on Azure. | | `api_version` | Optional[str] | 2023-05-15 | The version of the API to use. | | `azure_deployment` | str | text-embedding-ada-002 | The name of the model deployed on Azure. The default model is text-embedding-ada-002. | | `dimensions` | Optional[int] | None | The number of dimensions of the resulting embeddings. Only supported in text-embedding-3 and later models. | | `api_key` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The Azure OpenAI API key. You can set it with an environment variable `AZURE_OPENAI_API_KEY`, or pass with this parameter during initialization. | | `azure_ad_token` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_AD_TOKEN', strict=False) | Microsoft Entra ID token. See Microsoft's [Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) documentation for more information. Previously called Azure Active Directory. | | `organization` | Optional[str] | None | Your organization ID. See OpenAI's [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) for more information. | | `prefix` | str | | A string to add at the beginning of each text. | | `suffix` | str | | A string to add at the end of each text. | | `batch_size` | int | 32 | Number of documents to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when running. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | \n | Separator used to concatenate the metadata fields to the document text. | | `timeout` | Optional[float] | None | The timeout for `AzureOpenAI` client calls, in seconds. If not set, defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries to contact AzureOpenAI after an internal error. If not set, defaults to either the `OPENAI_MAX_RETRIES` environment variable or to 5 retries. | | `default_headers` | Optional[Dict[str, str]] | None | Default headers to send to the AzureOpenAI client. | | `azure_ad_token_provider` | Optional[AzureADTokenProvider] | None | A function that returns an Azure Active Directory token, will be invoked on every request. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | | `raise_on_failure` | bool | False | Whether to raise an exception if the embedding request fails. If `False`, the component will log the error and continue processing the remaining documents. If `True`, it will raise an exception on failure. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :---------- | :------------- | :--------------------------- | | `documents` | List[Document] | A list of documents to embed. | ## Related Information - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) - [AzureOpenAITextEmbedder](/docs/reference/pipeline-components/integrations/azure/AzureOpenAITextEmbedder.mdx) --- ## AzureOpenAIGenerator Generate text using OpenAI's large language models (LLMs) hosted on Azure. It works with GPT-4-type models and supports streaming responses. ## Key Features - Generates text using OpenAI GPT-4-type models hosted on Azure OpenAI. - Accepts a text prompt and returns generated text replies. - Supports streaming responses token by token. - Customizable generation behavior through `generation_kwargs` (temperature, max_tokens, and others). - Accepts Azure Active Directory (Entra ID) tokens for authentication in addition to API keys. ## Configuration :::tip Authentication To use this component, connect with Azure OpenAI first. For detailed instructions, see [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx). ::: 1. Drag the `AzureOpenAIGenerator` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. You can set the API key and endpoint through environment variables (`AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`) or directly in the configuration panel. ## Connections `AzureOpenAIGenerator` accepts a text prompt as input. It outputs a list of generated text responses and a list of metadata dictionaries. Connect a `PromptBuilder` to the `prompt` input to build dynamic prompts. Connect the `replies` output to `AnswerBuilder` for answer extraction. 1. Drag the `AzureOpenAIGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Azure endpoint and deployment name (model name). - Enter your API key, or set it using the `AZURE_OPENAI_API_KEY` environment variable. - Set `generation_kwargs` to configure model behavior, such as `temperature` and `max_completion_tokens`. - Optionally, set a `system_prompt` to configure model behavior. 4. Go to the **Advanced** tab to configure additional settings, such as `timeout`, `max_retries`, `organization`, `streaming_callback`, `http_client_kwargs`, and `default_headers`. ## Source Code To check this component's source code, open [`azure.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/azure.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `AzureOpenAIGenerator` receives a text `prompt` string. Connect a `PromptBuilder`'s `prompt` output to its `prompt` input. It outputs a list of text `replies` and a list of metadata dictionaries. Connect its `replies` output to an `AnswerBuilder` or use it as the pipeline's final output. ## Usage Examples ### Basic Configuration ```yaml azure_generator: type: haystack.components.generators.azure.AzureOpenAIGenerator init_parameters: azure_endpoint: ${AZURE_OPENAI_ENDPOINT} azure_deployment: gpt-4.1-mini api_version: 2024-12-01-preview generation_kwargs: temperature: 0.7 max_completion_tokens: 500 ``` Here's an example RAG pipeline using `AzureOpenAIGenerator`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} top_k: 10 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a helpful assistant. Answer the question based on the provided documents. If the documents don't contain the answer, say so. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{question}} Answer: azure_generator: type: haystack.components.generators.azure.AzureOpenAIGenerator init_parameters: azure_endpoint: ${AZURE_OPENAI_ENDPOINT} azure_deployment: gpt-4.1-mini api_version: 2024-12-01-preview generation_kwargs: temperature: 0.7 max_completion_tokens: 500 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: prompt_builder.documents - sender: bm25_retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: azure_generator.prompt - sender: azure_generator.replies receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - prompt_builder.question - answer_builder.query outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :------------------------------------ | | `prompt` | str | The text prompt to generate text from. | ### Outputs | Parameter | Type | Description | | :-------- | :--------- | :--------------------------------------------------------------------------------------------------------------------------- | | `replies` | List[str] | A list of generated text responses. | | `meta` | List[Dict] | A list of metadata dictionaries for each generated response, including model information, tokens used, and finish reason. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :---------------------- | :----------------------------- | :--------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `azure_endpoint` | Optional[str] | None | The endpoint of the deployed model, for example `https://example-resource.azure.openai.com/`. Can also be set via the `AZURE_OPENAI_ENDPOINT` environment variable. | | `api_version` | Optional[str] | 2024-12-01-preview | The version of the Azure OpenAI API to use. Defaults to 2024-12-01-preview. | | `azure_deployment` | Optional[str] | gpt-4.1-mini | The deployment name of the model, usually the model name. | | `api_key` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The API key to use for authentication. | | `azure_ad_token` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_AD_TOKEN', strict=False) | Azure Active Directory token for authentication. See [Microsoft Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id). | | `organization` | Optional[str] | None | Your organization ID. For help, see [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) as an argument. | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If not provided, the generator uses the default system prompt. | | `timeout` | Optional[float] | 30.0 | Timeout for AzureOpenAI client. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30. | | `max_retries` | Optional[int] | 5 | Maximum retries to establish contact with AzureOpenAI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the Azure OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat) for more details. Some supported parameters: `max_completion_tokens` (upper bound for tokens generated), `temperature` (sampling temperature), `top_p` (nucleus sampling probability mass), `n` (number of completions per prompt), `stop` (stop sequences), `presence_penalty`, `frequency_penalty`, `logit_bias`. | | `default_headers` | Optional[Dict[str, str]] | None | Default headers to use for the AzureOpenAI client. | | `azure_ad_token_provider` | Optional[AzureADTokenProvider] | None | A function that returns an Azure Active Directory token, invoked on every request. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :------------------ | :----------------------- | :------ | :---------------------------------------------------------------------------------------------------------- | | `prompt` | str | | The text prompt to generate text from. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional parameters for text generation. These override the parameters set during component initialization. | ## Related Information - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AzureOpenAIResponsesChatGenerator Generate text using OpenAI's Responses API on Azure with support for reasoning models. The default model is `gpt-5-mini`. ## Key Features - Uses OpenAI's Responses API through Azure OpenAI services. - Supports GPT-5 and o-series reasoning models (like o1, o3-mini) deployed on Azure. - Supports multi-turn conversations using `previous_response_id`. - Supports structured output generation through Pydantic models or JSON schemas. - Supports tool calling with `Tool` objects, a `Toolset`, or OpenAI/MCP tool definitions. - Supports reasoning model configuration with effort levels (`low`, `medium`, `high`) and reasoning summaries. ## Configuration :::tip Authentication To use this component, connect with Azure OpenAI first. For details, see [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx). ::: 1. Drag the `AzureOpenAIResponsesChatGenerator` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. You can set the API key and endpoint through environment variables (`AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`) or directly in the configuration panel. 1. Drag the `AzureOpenAIResponsesChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Azure endpoint and deployment name (model name). - Enter your API key, or set it using the `AZURE_OPENAI_API_KEY` environment variable. - Set `generation_kwargs` to configure model behavior, such as `temperature` or `reasoning` effort. 4. Go to the **Advanced** tab to configure additional settings, such as `timeout`, `max_retries`, `organization`, `streaming_callback`, `tools`, `tools_strict`, and `http_client_kwargs`. ### Reasoning Support You can configure reasoning behavior using the `reasoning` parameter in `generation_kwargs`. The `reasoning` parameter accepts: - `effort`: Specifies the level of reasoning effort for the model. Possible values are: `"low"`, `"medium"`, or `"high"`. - `summary`: Specifies how to generate reasoning summaries. You can choose: `"auto"` or `"generate_summary": True/False`. :::info OpenAI does not return the actual reasoning tokens, but you can view the summary if enabled. For more details, see the [OpenAI Reasoning documentation](https://platform.openai.com/docs/guides/reasoning). ::: ### Multi-turn Conversations The Responses API supports multi-turn conversations using `previous_response_id`. You can pass the response ID from a previous turn to maintain conversation context. ### Structured Output `AzureOpenAIResponsesChatGenerator` supports structured output generation through the `text_format` and `text` parameters in `generation_kwargs`: - **`text_format`**: Pass a Pydantic model to define the structure. - **`text`**: Pass a JSON schema directly. :::info Model Compatibility and Limitations - Both Pydantic models and JSON schemas are supported for latest models starting from GPT-4o. - If both `text_format` and `text` are provided, `text_format` takes precedence and the JSON schema passed to `text` is ignored. - Streaming is not supported when using structured outputs. - Older models only support basic JSON mode through `{"type": "json_object"}`. For details, see [OpenAI JSON mode documentation](https://platform.openai.com/docs/guides/structured-outputs#json-mode). - For complete information, check the [Azure OpenAI Structured Outputs documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/structured-outputs). ::: ## Connections `AzureOpenAIResponsesChatGenerator` receives a list of `ChatMessage` objects. Connect a `ChatPromptBuilder`'s `prompt` output to its `messages` input. It outputs a list of `ChatMessage` objects as `replies`. Connect its `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`, or use it as the pipeline's final output. ## Source Code To check this component's source code, open [`azure_responses.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/azure_responses.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml AzureOpenAIResponsesChatGenerator: type: haystack.components.generators.chat.azure_responses.AzureOpenAIResponsesChatGenerator init_parameters: azure_deployment: gpt-5-mini api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false generation_kwargs: reasoning: effort: low summary: auto tools_strict: false ``` This is a RAG pipeline where `AzureOpenAIResponsesChatGenerator` sends the generated replies to `DeepsetAnswerBuilder` through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false AzureOpenAIResponsesChatGenerator: type: haystack.components.generators.chat.azure_responses.AzureOpenAIResponsesChatGenerator init_parameters: azure_endpoint: azure_deployment: gpt-5-mini api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false organization: streaming_callback: timeout: max_retries: generation_kwargs: reasoning: effort: low summary: auto tools: tools_strict: false http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: AzureOpenAIResponsesChatGenerator.messages - sender: AzureOpenAIResponsesChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :------------------ | :----------------------------------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses/create). | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]] | None | A list of Tool objects, a Toolset, or OpenAI/MCP tool definitions that the model can use. Each tool should have a unique name. If set, it will override the `tools` parameter set during component initialization. Note: You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | Optional[Bool] | None | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the parameters field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter set during component initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :--------------------------- | | `replies` | List[ChatMessage] | The responses from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------ | :----------------------------------------------- | :-------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `azure_endpoint` | Optional[str] | None | The endpoint of the deployed model, for example `"https://example-resource.azure.openai.com/"`. Can be set with `AZURE_OPENAI_ENDPOINT` env var. | | `azure_deployment` | str | gpt-5-mini | The deployment of the model, usually the model name. | | `api_key` | Optional[Union[Secret, Callable]] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The API key to use for authentication. Can be a `Secret` object containing the API key, a `Secret` object containing the [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id), or a function that returns an Azure Active Directory token. | | `organization` | Optional[str] | None | Your organization ID. For help, see [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) as an argument. | | `timeout` | Optional[float] | None | Timeout for OpenAI client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model. These parameters are sent directly to the OpenAI endpoint. For details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses). Some of the supported parameters: `temperature`, `top_p`, `previous_response_id` (for multi-turn conversations), `text_format` (Pydantic model for structured outputs), `text` (JSON schema for structured outputs), `reasoning` (a dictionary with `effort` and `summary` keys). | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]] | None | A list of tools, a Toolset, or OpenAI/MCP tool definitions for which the model can prepare calls. Note: You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | bool | False | Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. In Response API, tool calls are strict by default. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :------------------ | :----------------------------------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses/create). | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]] | None | A list of tools, a Toolset, or OpenAI/MCP tool definitions for which the model can prepare calls. If set, it overrides the `tools` parameter in pipeline configuration. Note: You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | Optional[bool] | None | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ## Related Information - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) - [AzureOpenAIChatGenerator](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIChatGenerator.mdx) --- ## AzureOpenAITextEmbedder Embed strings, like user queries, using OpenAI models deployed on Azure. ## Key Features - Computes vector embeddings for text strings, such as user queries, using Azure OpenAI models. - Enables semantic-based document retrieval in query pipelines. - Returns usage metadata along with the embedding. - For a list of supported models, see [Azure documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/foundry-models/concepts/models-sold-directly-by-azure?pivots=azure-openai&source=recommendations). ## Configuration - Embeds a single string using OpenAI embedding models deployed on Azure. - Returns the embedding as a list of floats along with model usage metadata. - Use `AzureOpenAIDocumentEmbedder` to embed documents in indexes. - Supports a wide range of Azure OpenAI embedding models. ## Configuration :::tip Authentication You need an Azure OpenAI API key to use this component. Connect to your Azure OpenAI account. For more information, see [Using Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx). ::: 1. Drag the `AzureOpenAITextEmbedder` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. You can set the API key and endpoint through environment variables (`AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`) or directly in the configuration panel. ## Connections `AzureOpenAITextEmbedder` accepts a text string as input and outputs a list of floats representing the text embedding and usage metadata. Connect the pipeline's query input to the `text` input. Connect the `embedding` output to an embedding retriever's `query_embedding` input to find matching documents. 1. Drag the `AzureOpenAITextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter the Azure endpoint and deployment name (embedding model name). - Enter your API key, or set it using the `AZURE_OPENAI_API_KEY` environment variable. 4. Go to the **Advanced** tab to configure additional settings, such as `dimensions`, `prefix`, `suffix`, `timeout`, `max_retries`, `organization`, `http_client_kwargs`, and `default_headers`. ## Source Code To check this component's source code, open [`azure_text_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/azure_text_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `AzureOpenAITextEmbedder` receives a text string to embed. Connect the `query` output of the `Input` component to its `text` input. It outputs a list of floats representing the embedding, along with usage metadata. Connect its `embedding` output to an embedding retriever's `query_embedding` input. ## Usage Examples ### Basic Configuration ```yaml AzureOpenAITextEmbedder: type: haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder init_parameters: azure_deployment: text-embedding-ada-002 api_key: type: env_var env_vars: - AZURE_OPENAI_API_KEY strict: false ``` ### In a Pipeline This is an example of a query pipeline that uses `AzureOpenAITextEmbedder` to embed the user query and send it to the retriever. ```yaml # haystack-pipeline components: # ... query_embedder: type: haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder init_parameters: azure_endpoint: "https://your-company.azure.openai.com/" azure_deployment: "text-embedding-ada-002" #this is the name of the model you want to use retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: generator: type: haystack.components.generators.azure.AzureOpenAIGenerator init_parameters: generation_kwargs: temperature: 0.0 azure_deployment: gpt-35-turbo #this is the model you want to use answer_builder: init_parameters: {} type: haystack.components.builders.answer_builder.AnswerBuilder connections: # Defines how the components are connected - sender: query_embedder.embedding # AzureOpenAITextEmbedder sends the embedded query to the retriever receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies inputs: query: # ... - "query_embedder.text" # TextEmbedder needs query as input and it's not getting it - "retriever.query" # from any component it's connected to, so it needs to receive it from the pipeline. - "prompt_builder.question" - "answer_builder.query" ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :------------- | | `text` | str | Text to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :------------- | :----------------------------------------------------------------------------- | | `embedding` | List[float] | A list of floats representing the embedding of the input text. | | `meta` | Dict[str, Any] | Information about the usage of the model, including model name and token usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :---------------------- | :----------------------------- | :-------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `azure_endpoint` | Optional[str] | None | The endpoint of the model deployed on Azure. | | `api_version` | Optional[str] | 2023-05-15 | The version of the API to use. | | `azure_deployment` | str | text-embedding-ada-002 | The name of the model deployed on Azure. The default model is text-embedding-ada-002. | | `dimensions` | Optional[int] | None | The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. | | `api_key` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The Azure OpenAI API key. You can set it with an environment variable `AZURE_OPENAI_API_KEY`, or pass with this parameter during initialization. | | `azure_ad_token` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_AD_TOKEN', strict=False) | Microsoft Entra ID token. See Microsoft's [Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id) documentation for more information. Previously called Azure Active Directory. | | `organization` | Optional[str] | None | Your organization ID. See OpenAI's [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) for more information. | | `timeout` | Optional[float] | None | The timeout for `AzureOpenAI` client calls, in seconds. If not set, defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries to contact AzureOpenAI after an internal error. If not set, defaults to either the `OPENAI_MAX_RETRIES` environment variable, or to 5 retries. | | `prefix` | str | | A string to add at the beginning of each text. | | `suffix` | str | | A string to add at the end of each text. | | `default_headers` | Optional[Dict[str, str]] | None | Default headers to send to the AzureOpenAI client. | | `azure_ad_token_provider` | Optional[AzureADTokenProvider] | None | A function that returns an Azure Active Directory token, will be invoked on every request. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :------------- | | `text` | str | Text to embed. | ## Related Information - [Use Azure OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-azure-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) - [AzureOpenAIDocumentEmbedder](/docs/reference/pipeline-components/integrations/azure/AzureOpenAIDocumentEmbedder.mdx) --- ## AzureAISearchBM25Retriever Retrieve documents from an `AzureAISearchDocumentStore` using BM25 keyword search. ## Key Features - Keyword-based full-text retrieval from Azure AI Search. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports advanced Azure AI Search query types, including `simple`, `full`, and `semantic`. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `AzureAISearchBM25Retriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `AzureAISearchDocumentStore` with your Azure AI Search instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy` and additional Azure AI Search query options. ## Connections `AzureAISearchBM25Retriever` receives the user query as a text string, typically from the `Input` component. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`bm25_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/azure_ai_search/src/haystack_integrations/components/retrievers/azure_ai_search/bm25_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AzureAISearchBM25Retriever: type: haystack_integrations.components.retrievers.azure_ai_search.bm25_retriever.AzureAISearchBM25Retriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.azure_ai_search.document_store.AzureAISearchDocumentStore init_parameters: api_key: type: env_var env_vars: - AZURE_SEARCH_API_KEY strict: false azure_endpoint: type: env_var env_vars: - AZURE_SEARCH_SERVICE_ENDPOINT strict: false index_name: my-index ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AzureAISearchDocumentStore | | An instance of `AzureAISearchDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [AzureAISearchEmbeddingRetriever](/docs/reference/pipeline-components/integrations/azure-ai-search/AzureAISearchEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AzureAISearchEmbeddingRetriever Retrieve documents from an `AzureAISearchDocumentStore` using vector similarity search. ## Key Features - Dense vector-based retrieval from Azure AI Search using vector similarity. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports advanced Azure AI Search query types including semantic search. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `AzureAISearchEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `AzureAISearchDocumentStore` with your Azure AI Search instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy` and additional Azure AI Search options. ## Connections `AzureAISearchEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/azure_ai_search/src/haystack_integrations/components/retrievers/azure_ai_search/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AzureAISearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.azure_ai_search.embedding_retriever.AzureAISearchEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.azure_ai_search.document_store.AzureAISearchDocumentStore init_parameters: api_key: type: env_var env_vars: - AZURE_SEARCH_API_KEY strict: false azure_endpoint: type: env_var env_vars: - AZURE_SEARCH_SERVICE_ENDPOINT strict: false index_name: my-index ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AzureAISearchDocumentStore | | An instance of `AzureAISearchDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [AzureAISearchBM25Retriever](/docs/reference/pipeline-components/integrations/azure-ai-search/AzureAISearchBM25Retriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## AzureAISearchHybridRetriever Retrieve documents from an `AzureAISearchDocumentStore` using a combination of BM25 keyword search and vector similarity search. ## Key Features - Hybrid retrieval combining BM25 keyword search and dense vector search from Azure AI Search. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports advanced Azure AI Search options including semantic ranking. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `AzureAISearchHybridRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `AzureAISearchDocumentStore` with your Azure AI Search instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy` and additional Azure AI Search options. ## Connections `AzureAISearchHybridRetriever` receives both a text query string and a query embedding vector as inputs. Connect these from the `Input` component and a text embedder respectively. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`hybrid_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/azure_ai_search/src/haystack_integrations/components/retrievers/azure_ai_search/hybrid_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AzureAISearchHybridRetriever: type: haystack_integrations.components.retrievers.azure_ai_search.hybrid_retriever.AzureAISearchHybridRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.azure_ai_search.document_store.AzureAISearchDocumentStore init_parameters: api_key: type: env_var env_vars: - AZURE_SEARCH_API_KEY strict: false azure_endpoint: type: env_var env_vars: - AZURE_SEARCH_SERVICE_ENDPOINT strict: false index_name: my-index ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query for keyword-based search. | | `query_embedding` | List[float] | The embedding of the query for vector-based search. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | AzureAISearchDocumentStore | | An instance of `AzureAISearchDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query for keyword-based search. | | `query_embedding` | List[float] | | The embedding of the query for vector-based search. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [AzureAISearchEmbeddingRetriever](/docs/reference/pipeline-components/integrations/azure-ai-search/AzureAISearchEmbeddingRetriever.mdx) - [AzureAISearchBM25Retriever](/docs/reference/pipeline-components/integrations/azure-ai-search/AzureAISearchBM25Retriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## BraveWebSearch Search the web using the [Brave Search API](https://brave.com/search/api/) and return results as Haystack Documents. ## Key Features - Web search powered by the privacy-focused Brave Search engine. - Returns search results as Haystack `Document` objects with content and metadata. - Also returns raw links alongside documents for downstream use. - Configurable number of results with `top_k`. - Supports locale filtering with `country` and `search_lang` parameters. - Configurable timeout and retry logic. ## Configuration 1. Drag the `BraveWebSearch` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Brave Search API key and set it as `api_key`. Use `BRAVE_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [brave.com/search/api](https://brave.com/search/api/). 2. Set `top_k` to control the maximum number of search results to return. 4. Go to the **Advanced** tab to configure `country`, `search_lang`, `timeout`, `max_retries`, and `extra_params`. ## Connections `BraveWebSearch` receives a query string and outputs a list of `Document` objects containing search result content and a list of raw URLs. Connect its `documents` output to a `PromptBuilder` or ranker to use the results in a pipeline. ## Source Code To check this component's source code, open [`brave_websearch.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/brave/src/haystack_integrations/components/websearch/brave/brave_websearch.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml BraveWebSearch: type: haystack_integrations.components.websearch.brave.brave_websearch.BraveWebSearch init_parameters: api_key: type: env_var env_vars: - BRAVE_API_KEY strict: false top_k: 10 timeout: 10 max_retries: 3 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: BraveWebSearch: type: haystack_integrations.components.websearch.brave.brave_websearch.BraveWebSearch init_parameters: api_key: type: env_var env_vars: - BRAVE_API_KEY strict: false top_k: 5 prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: | Answer based on these web search results: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini connections: - sender: BraveWebSearch.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: llm.messages max_runs_per_component: 100 metadata: {} inputs: query: - BraveWebSearch.query - prompt_builder.question ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The search query to send to Brave Search. | | `top_k` | Optional[int] | The maximum number of results to return. Overrides the init-time `top_k` if provided. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The search results as Haystack Documents. | | `links` | List[str] | The URLs of the search results. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("BRAVE_API_KEY")` | The Brave Search API key. | | `top_k` | Optional[int] | 10 | The maximum number of search results to return. | | `country` | Optional[str] | None | The country code for localized search results (for example, `US`, `GB`). | | `search_lang` | Optional[str] | None | The language code for search results (for example, `en`, `de`). | | `extra_params` | Optional[Dict[str, Any]] | None | Additional Brave Search API parameters. | | `timeout` | int | 10 | Request timeout in seconds. | | `max_retries` | int | 3 | Maximum number of retries on API errors. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The search query to send to Brave Search. | | `top_k` | Optional[int] | None | The maximum number of results to return. Overrides the init-time `top_k`. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChonkieRecursiveDocumentSplitter Split documents into chunks using recursive splitting rules with the [Chonkie](https://github.com/chonkie-ai/chonkie) chunking library. This splitter tries progressively finer separators (paragraphs, then sentences, then words) to create chunks that stay within the token limit while preserving as much semantic structure as possible. ## Key Features - Recursively tries different splitting separators from coarser to finer granularity. - Supports custom recursive splitting rules via `RecursiveRules`. - Configurable minimum characters per chunk to prevent very small fragments. - Preserves page break information and source document metadata. ## Configuration 1. Drag the `ChonkieRecursiveDocumentSplitter` component onto the canvas from the Component Library. 2. Configure the `chunk_size` to control the maximum number of tokens per chunk. 3. Optionally provide custom `rules` to control the splitting hierarchy. ## Connections `ChonkieRecursiveDocumentSplitter` receives a list of `Document` objects as input. It outputs a list of smaller `Document` objects (chunks) you can connect to a document embedder. ## Source Code To check this component's source code, open [`recursive_splitter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chonkie/src/haystack_integrations/components/preprocessors/chonkie/recursive_splitter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChonkieRecursiveDocumentSplitter: type: haystack_integrations.components.preprocessors.chonkie.recursive_splitter.ChonkieRecursiveDocumentSplitter init_parameters: tokenizer: character chunk_size: 512 min_characters_per_chunk: 24 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to split recursively. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of document chunks with updated metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `tokenizer` | str | `character` | The tokenizer to use for counting tokens. Use `character` for character-based counting, or a model name (for example, `gpt2`) for model-specific tokenization. | | `chunk_size` | int | `2048` | The maximum number of tokens per chunk. | | `min_characters_per_chunk` | int | `24` | The minimum number of characters required for a chunk to be kept. | | `rules` | Optional[RecursiveRules or Dict] | None | Custom recursive splitting rules. If None, uses default rules (paragraphs → sentences → words). | | `skip_empty_documents` | bool | `True` | Whether to skip documents with no content. | | `page_break_character` | str | `\f` | The character used to represent page breaks in document text. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | The documents to split. | ## Related Information - [ChonkieSentenceDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSentenceDocumentSplitter.mdx) - [ChonkieTokenDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieTokenDocumentSplitter.mdx) - [ChonkieSemanticDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSemanticDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChonkieSemanticDocumentSplitter Split documents into semantically coherent chunks using the [Chonkie](https://github.com/chonkie-ai/chonkie) chunking library. This splitter groups sentences with similar semantic content together, creating chunks that are thematically consistent rather than just size-limited. ## Key Features - Groups sentences by semantic similarity using an embedding model. - Creates chunks that are semantically coherent rather than just fixed-size. - Configurable similarity threshold to control how aggressively sentences are grouped. - Uses a Savitzky-Golay filter to smooth semantic similarity signals and detect topic boundaries. - Loads the embedding model lazily on the first `run()` call. ## Configuration 1. Drag the `ChonkieSemanticDocumentSplitter` component onto the canvas from the Component Library. 2. Configure the `embedding_model` to the model you want to use for computing sentence similarity. 3. Adjust the `threshold` to control how similar adjacent sentences must be to remain in the same chunk. Lower values create more, smaller chunks; higher values create fewer, larger chunks. ## Connections `ChonkieSemanticDocumentSplitter` receives a list of `Document` objects as input. It outputs a list of smaller `Document` objects (chunks) you can connect to a document embedder. ## Source Code To check this component's source code, open [`semantic_splitter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chonkie/src/haystack_integrations/components/preprocessors/chonkie/semantic_splitter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChonkieSemanticDocumentSplitter: type: haystack_integrations.components.preprocessors.chonkie.semantic_splitter.ChonkieSemanticDocumentSplitter init_parameters: embedding_model: minishlab/potion-base-32M threshold: 0.8 chunk_size: 512 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to split into semantically coherent chunks. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of semantically grouped document chunks with updated metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `embedding_model` | Any | `minishlab/potion-base-32M` | The embedding model to use for computing sentence similarity. Can be a model name string or a model instance. | | `threshold` | float | `0.8` | The cosine similarity threshold for grouping sentences. Sentences with similarity above this value are kept in the same chunk. | | `chunk_size` | int | `2048` | The maximum number of tokens per chunk. | | `similarity_window` | int | `3` | The number of adjacent sentences to compare when computing similarity. | | `min_sentences_per_chunk` | int | `1` | The minimum number of sentences to include in each chunk. | | `min_characters_per_sentence` | int | `24` | The minimum number of characters a sentence must have to be included. | | `delim` | Any | None | Custom sentence delimiters. If None, uses default sentence-ending punctuation. | | `include_delim` | str | `prev` | Where to include the delimiter in the chunk. One of `prev` or `next`. | | `skip_window` | int | `0` | The window size for skipping sentences with low similarity. | | `filter_window` | int | `5` | The window size for the Savitzky-Golay smoothing filter. | | `filter_polyorder` | int | `3` | The polynomial order for the Savitzky-Golay smoothing filter. | | `filter_tolerance` | float | `0.2` | The tolerance for detecting topic boundary peaks after smoothing. | | `skip_empty_documents` | bool | `True` | Whether to skip documents with no content. | | `page_break_character` | str | `\f` | The character used to represent page breaks in document text. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | The documents to split. | ## Related Information - [ChonkieSentenceDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSentenceDocumentSplitter.mdx) - [ChonkieTokenDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieTokenDocumentSplitter.mdx) - [ChonkieRecursiveDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieRecursiveDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChonkieSentenceDocumentSplitter Split documents into chunks at sentence boundaries using the [Chonkie](https://github.com/chonkie-ai/chonkie) chunking library. Use this component in indexing pipelines to prepare documents for embedding and retrieval. ## Key Features - Splits text at sentence boundaries to preserve semantic coherence within chunks. - Supports multiple tokenizer backends including character-based, word-based, and model-specific tokenizers. - Configurable minimum sentences per chunk and minimum characters per sentence. - Preserves page break information and source document metadata. - Adds split metadata to each chunk: `source_id`, `page_number`, `split_id`, `split_idx_start`, `split_idx_end`, and `token_count`. ## Configuration 1. Drag the `ChonkieSentenceDocumentSplitter` component onto the canvas from the Component Library. 2. Configure the `chunk_size` to control the maximum number of tokens per chunk. 3. Optionally set `chunk_overlap` to include overlapping content between adjacent chunks for better retrieval continuity. ## Connections `ChonkieSentenceDocumentSplitter` receives a list of `Document` objects as input from a document converter or file router. It outputs a list of smaller `Document` objects (chunks) you can connect to a document embedder. ## Source Code To check this component's source code, open [`sentence_splitter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chonkie/src/haystack_integrations/components/preprocessors/chonkie/sentence_splitter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChonkieSentenceDocumentSplitter: type: haystack_integrations.components.preprocessors.chonkie.sentence_splitter.ChonkieSentenceDocumentSplitter init_parameters: tokenizer: character chunk_size: 512 chunk_overlap: 50 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to split into sentence-based chunks. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of document chunks with updated metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `tokenizer` | str | `character` | The tokenizer to use for counting tokens. Use `character` for character-based counting, or a model name (for example, `gpt2`) for model-specific tokenization. | | `chunk_size` | int | `2048` | The maximum number of tokens per chunk. | | `chunk_overlap` | int | `0` | The number of tokens to overlap between adjacent chunks. | | `min_sentences_per_chunk` | int | `1` | The minimum number of sentences to include in each chunk. | | `min_characters_per_sentence` | int | `12` | The minimum number of characters a sentence must have to be included. | | `approximate` | bool | `False` | Whether to use approximate token counting for faster processing. | | `delim` | Any | None | Custom sentence delimiters. If None, uses default sentence-ending punctuation. | | `include_delim` | str | `prev` | Where to include the delimiter in the chunk. One of `prev` or `next`. | | `skip_empty_documents` | bool | `True` | Whether to skip documents with no content. | | `page_break_character` | str | `\f` | The character used to represent page breaks in document text. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | The documents to split. | ## Related Information - [ChonkieTokenDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieTokenDocumentSplitter.mdx) - [ChonkieRecursiveDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieRecursiveDocumentSplitter.mdx) - [ChonkieSemanticDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSemanticDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChonkieTokenDocumentSplitter Split documents into fixed-size token chunks using the [Chonkie](https://github.com/chonkie-ai/chonkie) chunking library. Use this component in indexing pipelines when you need predictable, token-aligned chunks rather than sentence-boundary splitting. ## Key Features - Splits text into chunks of a fixed maximum token size. - Supports multiple tokenizer backends including character-based and model-specific tokenizers. - Configurable overlap between adjacent chunks. - Preserves page break information and source document metadata. ## Configuration 1. Drag the `ChonkieTokenDocumentSplitter` component onto the canvas from the Component Library. 2. Configure the `chunk_size` to control the maximum number of tokens per chunk. 3. Optionally set `chunk_overlap` to include overlapping content between adjacent chunks. ## Connections `ChonkieTokenDocumentSplitter` receives a list of `Document` objects as input from a document converter or file router. It outputs a list of smaller `Document` objects (chunks) you can connect to a document embedder. ## Source Code To check this component's source code, open [`token_splitter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chonkie/src/haystack_integrations/components/preprocessors/chonkie/token_splitter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChonkieTokenDocumentSplitter: type: haystack_integrations.components.preprocessors.chonkie.token_splitter.ChonkieTokenDocumentSplitter init_parameters: tokenizer: character chunk_size: 512 chunk_overlap: 50 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to split into token-based chunks. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of document chunks with updated metadata. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `tokenizer` | str | `character` | The tokenizer to use for counting tokens. Use `character` for character-based counting, or a model name (for example, `gpt2`) for model-specific tokenization. | | `chunk_size` | int | `2048` | The maximum number of tokens per chunk. | | `chunk_overlap` | int | `0` | The number of tokens to overlap between adjacent chunks. | | `skip_empty_documents` | bool | `True` | Whether to skip documents with no content. | | `page_break_character` | str | `\f` | The character used to represent page breaks in document text. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | The documents to split. | ## Related Information - [ChonkieSentenceDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSentenceDocumentSplitter.mdx) - [ChonkieRecursiveDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieRecursiveDocumentSplitter.mdx) - [ChonkieSemanticDocumentSplitter](/docs/reference/pipeline-components/integrations/chonkie/ChonkieSemanticDocumentSplitter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChromaEmbeddingRetriever Retrieve documents from a `ChromaDocumentStore` using vector embeddings. ## Key Features - Dense vector-based retrieval from a [Chroma](https://docs.trychroma.com/) vector database. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `ChromaEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `ChromaDocumentStore` with your Chroma instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`. ## Connections `ChromaEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chroma/src/haystack_integrations/components/retrievers/chroma/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChromaEmbeddingRetriever: type: haystack_integrations.components.retrievers.chroma.retriever.ChromaEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.chroma.document_store.ChromaDocumentStore init_parameters: collection_name: documents host: localhost port: 8000 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: ChromaEmbeddingRetriever: type: haystack_integrations.components.retrievers.chroma.retriever.ChromaEmbeddingRetriever init_parameters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.chroma.document_store.ChromaDocumentStore init_parameters: collection_name: documents host: localhost port: 8000 connections: [] max_runs_per_component: 100 metadata: {} inputs: query_embedding: - ChromaEmbeddingRetriever.query_embedding outputs: documents: ChromaEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | ChromaDocumentStore | | An instance of `ChromaDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ChromaQueryTextRetriever Retrieve documents from a `ChromaDocumentStore` using text queries. ## Key Features - Text-based retrieval from a [Chroma](https://docs.trychroma.com/) vector database using Chroma's built-in embedding and querying. - Chroma handles the embedding of the query text internally using the configured embedding function. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `ChromaQueryTextRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `ChromaDocumentStore` with your Chroma instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`. ## Connections `ChromaQueryTextRetriever` receives the user query as a text string, typically from the `Input` component. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/chroma/src/haystack_integrations/components/retrievers/chroma/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ChromaQueryTextRetriever: type: haystack_integrations.components.retrievers.chroma.retriever.ChromaQueryTextRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.chroma.document_store.ChromaDocumentStore init_parameters: collection_name: documents host: localhost port: 8000 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: ChromaQueryTextRetriever: type: haystack_integrations.components.retrievers.chroma.retriever.ChromaQueryTextRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.chroma.document_store.ChromaDocumentStore init_parameters: collection_name: documents host: localhost port: 8000 connections: [] max_runs_per_component: 100 metadata: {} inputs: query: - ChromaQueryTextRetriever.query outputs: documents: ChromaQueryTextRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | ChromaDocumentStore | | An instance of `ChromaDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CohereChatGenerator Complete chats using Cohere's models through the Cohere ClientV2 `chat` endpoint. ## Key Features - Uses Cohere's ClientV2 `chat` endpoint for chat completions. - Customizable generation through `generation_kwargs`, including temperature, citation quality, and more. - Supports tool calling with a list of tools or a Toolset. - Streaming support for token-by-token responses. ## Configuration 1. Drag the `CohereChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the Cohere model to use. Make sure is connected to your Cohere account. For details, see [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx). 4. Go to the **Advanced** tab to configure additional settings such as `generation_kwargs`, `tools`, `api_base_url`, and `streaming_callback`. ## Connections `CohereChatGenerator` receives a rendered prompt as a list of `ChatMessage` objects, typically from `ChatPromptBuilder`. It outputs a list of `ChatMessage` objects through its `replies` output. Connect its `replies` output to `DeepsetAnswerBuilder` through an `OutputAdapter` to build answers with references. See the usage example below for a complete pipeline. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/cohere/src/haystack_integrations/components/generators/cohere/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml CohereChatGenerator: type: haystack_integrations.components.generators.cohere.chat.chat_generator.CohereChatGenerator init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: command-r-08-2024 ``` ### Using the Component in a Pipeline This is a RAG chat pipeline with `CohereChatGenerator` sending replies to `DeepsetAnswerBuilder` through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false CohereChatGenerator: type: haystack_integrations.components.generators.cohere.chat.chat_generator.CohereChatGenerator init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: command-r-08-2024 streaming_callback: api_base_url: generation_kwargs: tools: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: CohereChatGenerator.messages - sender: CohereChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type |Default| Description | |-----------------|------------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |List[ChatMessage] | |List of `ChatMessage` instances representing the input messages. | |generation_kwargs|Optional[Dict[str, Any]] |None |Additional keyword arguments for chat generation. For details on the parameters supported by the Cohere API, refer to the Cohere [documentation](https://docs.cohere.com/reference/chat).| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. | ### Outputs |Parameter| Type |Default| Description | |---------|-----------------|-------|--------------------------------------------------------------------------------------------------------------------------| |replies |List[ChatMessage]| |A list of `ChatMessage` instances representing the generated responses.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------------------|-----------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var(['COHERE_API_KEY', 'CO_API_KEY'])|The API key for the Cohere API. | |model |str |command-r-08-2024 |The name of the model to use. You can use models from the `command` family. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. The callback function accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) as an argument. | |api_base_url |Optional[str] |None |The base URL of the Cohere API. | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model during generation. For a list of parameters, see [Cohere Chat endpoint](https://docs.cohere.com/reference/chat). Some of the parameters are: - 'messages': A list of messages between the user and the model, meant to give the model conversational context for responding to the user's message. - 'system_message': When specified, adds a system message at the beginning of the conversation. - 'citation_quality': Defaults to `accurate`. Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `accurate` results or `fast` results. - 'temperature': A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations.| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of Tool objects or a Toolset that the model can use. Each tool should have a unique name. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |-----------------|------------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |List[ChatMessage] | |List of `ChatMessage` instances representing the input messages. | |generation_kwargs|Optional[Dict[str, Any]] |None |Additional keyword arguments for chat generation. These parameters will potentially override the parameters passed in the __init__ method. For more details on the parameters supported by the Cohere API, refer to the Cohere [documentation](https://docs.cohere.com/reference/chat).| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. If set, it will override the `tools` parameter set during component initialization. | ## Related Information - [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CohereDocumentEmbedder Calculate document embeddings using Cohere models. Use this component in indexing pipelines to embed documents before writing them to a document store. ## Key Features - Uses Cohere models to embed a list of documents. - Adds the computed embeddings to the document's `embedding` metadata field. - Supports multiple Cohere embedding models. For a full list, see the [Cohere documentation](https://docs.cohere.com/docs/models#representation). - Configurable batch size and progress bar for large document sets. - Supports embedding additional metadata fields alongside document content. ## Configuration 1. Drag the `CohereDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the embedding model to use. Make sure is connected to your Cohere account. For details, see [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx). 2. Set the `input_type` to `search_document` for indexing pipelines. 4. Go to the **Advanced** tab to configure additional settings such as `truncate`, `timeout`, `batch_size`, `meta_fields_to_embed`, and `embedding_type`. ## Connections `CohereDocumentEmbedder` receives documents from converters such as `TextFileToDocument` or preprocessors such as `DocumentSplitter`. It outputs embedded documents through its `documents` output, which you connect to `DocumentWriter` to write them into a document store. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/cohere/src/haystack_integrations/components/embedders/cohere/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml CohereDocumentEmbedder: type: haystack_integrations.components.embedders.cohere.document_embedder.CohereDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: embed-english-v2.0 input_type: search_document api_base_url: https://api.cohere.com truncate: END timeout: 120 batch_size: 32 progress_bar: true embedding_separator: \n ``` ### Using the Component in an Index In this index, `CohereDocumentEmbedder` receives documents from `DocumentSplitter` and embeds them. It then sends the embedded documents to `DocumentWriter` that writes them into a document store. The index is configured to use the `embed-english-v2.0` model, which means `CohereTextEmbedder` used in the query pipeline must also use the `embed-english-v2.0` model. ```yaml # haystack-pipeline components: DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine policy: NONE CohereDocumentEmbedder: type: haystack_integrations.components.embedders.cohere.document_embedder.CohereDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: embed-english-v2.0 input_type: search_document api_base_url: https://api.cohere.com truncate: END timeout: 120 batch_size: 32 progress_bar: true meta_fields_to_embed: embedding_separator: \n embedding_type: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false connections: - sender: DocumentSplitter.documents receiver: CohereDocumentEmbedder.documents - sender: CohereDocumentEmbedder.documents receiver: DocumentWriter.documents - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs |Parameter| Type |Default| Description | |---------|--------------|-------|-------------------| |documents|List[Document]| |Documents to embed.| ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------| |documents|List[Document]| |Documents with their embeddings added to `embedding` field.| |meta |Dict[str, Any]| |Metadata related to the embedding process.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|------------------------|-----------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var(['COHERE_API_KEY', 'CO_API_KEY'])|The Cohere API key. | |model |str |embed-english-v2.0 |The name of the model to use. Supported Models are: `"embed-english-v3.0"`, `"embed-english-light-v3.0"`, `"embed-multilingual-v3.0"`, `"embed-multilingual-light-v3.0"`, `"embed-english-v2.0"`, `"embed-english-light-v2.0"`, `"embed-multilingual-v2.0"`. For supported models, see [Cohere model documentation](https://docs.cohere.com/docs/models#representation). | |input_type |str |search_document |Specifies the type of input you're giving to the model. Supported values are "search_document", "search_query", "classification" and "clustering". Not required for older versions of the embedding models (meaning any model lower than v3), but is required for more recent versions (meaning any model later than v2). | |api_base_url |str |https://api.cohere.com |The Cohere API Base url. | |truncate |str |END |Truncate embeddings that are too long from start or end, ("NONE"\|"START"\|"END"). Passing "START" discards the start of the input. "END" discards the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. If "NONE" is selected, when the input exceeds the maximum input token length, an error is returned.| |timeout |int |120 |Request timeout in seconds. | |batch_size |int |32 |The number of Documents to encode at once. | |progress_bar |bool |True |Whether to show a progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. | |meta_fields_to_embed|Optional[List[str]] |None |List of meta fields that should be embedded along with the Document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the Document text. | |embedding_type |Optional[EmbeddingTypes]|None |The type of embeddings to return. Defaults to float embeddings. Note that int8, uint8, binary, and ubinary are only valid for v3 models. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|-------------------| |documents|List[Document]| |Documents to embed.| ## Related Information - [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CohereGenerator Generate text using Cohere's models through the Cohere `generate` endpoint. :::info Cohere `generate` API Cohere discontinued the `generate` API, so this generator is a wrapper around `CohereChatGenerator` provided for backward compatibility. ::: ## Key Features - Wrapper around `CohereChatGenerator` for backward compatibility with the discontinued Cohere `generate` API. - Simple text generation: receives a prompt and returns a list of text replies. - Supports streaming via a callback function. - Customizable through additional keyword arguments passed to the model. ## Configuration 1. Drag the `CohereGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the Cohere model to use. Make sure is connected to your Cohere account. For details, see [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx). 4. Go to the **Advanced** tab to configure additional settings such as `streaming_callback`, `api_base_url`, and additional model kwargs. ## Connections `CohereGenerator` receives a rendered prompt string from `PromptBuilder`. It outputs a list of text replies through its `replies` output, which you connect to `DeepsetAnswerBuilder` to build answers with references. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/cohere/src/haystack_integrations/components/generators/cohere/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration This is a simple example showing how to configure `CohereGenerator`: ```yaml # haystack-pipeline components: CohereGenerator: type: haystack_integrations.components.generators.cohere.generator.CohereGenerator init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: command-r streaming_callback: api_base_url: ``` ### Using the Component in a Pipeline This pipeline uses `CohereGenerator` to generate replies to a question. It uses `DeepsetAnswerBuilder` to build the answers with references. It's also optimized for uploading files when testing it in Playground. ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true CohereGenerator: type: haystack_integrations.components.generators.cohere.generator.CohereGenerator init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: command-r streaming_callback: api_base_url: S3Downloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: file_root_path: file_extensions: file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key connections: # Defines how the components are connected - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: CohereGenerator.prompt - sender: CohereGenerator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: S3Downloader.documents - sender: S3Downloader.documents receiver: attachments_joiner.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" outputs: # Defines the output of your pipeline documents: "attachments_joiner.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs |Parameter|Type|Default| Description | |---------|----|-------|----------------------------------------------| |prompt |str | |The prompt with instructions for the model.| ### Outputs |Parameter| Type |Default| Description | |---------|--------------------|-------|-------------------------------------------------------------------------------------------------------------------------------------| |replies |List[str] | |A list of replies generated by the model.| |meta |List[Dict[str, Any]]| |Information about the request.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------|-----------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var(['COHERE_API_KEY', 'CO_API_KEY'])|Cohere API key. | |model |str |command-r |Cohere model to use for generation. | |streaming_callback|Optional[Callable]|None |Callback function that is called when a new token is received from the stream. For more information, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx).| |api_base_url |Optional[str] |None |Cohere base URL. | |**kwargs |Any | |Additional arguments passed to the model. These arguments are specific to the model. You can check them in model's documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|----------------------------------------------| |prompt |str | |The prompt with instructions for the model.| ## Related Information - [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CohereRanker Rank documents based on their semantic similarity to the query using Cohere models. ## Key Features - Uses Cohere's rerank endpoint to score documents by their relevance to the query. - Returns documents ordered from most to least semantically relevant. - Supports a configurable number of top results to return. - Works with additional metadata fields for more context during reranking. - For a list of supported ranking models, see the [Cohere documentation](https://docs.cohere.com/reference/rerank-1). ## Configuration 1. Drag the `CohereRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the Cohere ranking model to use. Make sure is connected to your Cohere account. For details, see [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx). 2. Set `top_k` to the maximum number of documents to return. 4. Go to the **Advanced** tab to configure additional settings such as `api_base_url`, `meta_fields_to_embed`, `meta_data_separator`, and `max_tokens_per_doc`. ## Connections `CohereRanker` receives documents from a retriever and the user query from `Input`. It outputs a ranked list of documents through its `documents` output. You can connect its output to `PromptBuilder` or use it as the pipeline's final document output. It works well after `DocumentJoiner` in hybrid retrieval pipelines that combine keyword and semantic search results. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/cohere/src/haystack_integrations/components/rankers/cohere/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml CohereRanker: type: haystack_integrations.components.rankers.cohere.ranker.CohereRanker init_parameters: model: rerank-v3.5 top_k: 10 api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false api_base_url: https://api.cohere.com meta_data_separator: \n max_tokens_per_doc: 4096 ``` ### Using the Component in a Pipeline This is an example of a document search pipeline where `CohereRanker` receives joined documents from both a keyword and a semantic retriever. It then ranks the documents based on their similarity to the user query and outputs them as the final result. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' truncate: normalize_embeddings: false timeout: backend_kwargs: CohereRanker: type: haystack_integrations.components.rankers.cohere.ranker.CohereRanker init_parameters: model: rerank-v3.5 top_k: 10 api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false api_base_url: https://api.cohere.com meta_fields_to_embed: meta_data_separator: \n max_tokens_per_doc: 4096 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: DeepsetNvidiaTextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: document_joiner.documents receiver: CohereRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - bm25_retriever.query - DeepsetNvidiaTextEmbedder.text - CohereRanker.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: CohereRanker.documents ``` ## Parameters ### Inputs |Parameter| Type |Default| Description | |---------|--------------|-------|--------------------------------------------------------------| |query |str | |The user query. | |documents|List[Document]| |The documents to rank. | |top_k |Optional[int] |None |The maximum number of documents you want the Ranker to return.| ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------| |documents|List[Document]| |List of Documents most similar to the given query in descending order of similarity.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|-------------------|-----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------| |model |str |rerank-v3.5 |Cohere model name. Check the list of supported models in the [Cohere documentation](https://docs.cohere.com/docs/models).| |top_k |int |10 |The maximum number of documents to return. | |api_key |Secret |Secret.from_env_var(['COHERE_API_KEY', 'CO_API_KEY'])|Cohere API key. | |api_base_url |str |https://api.cohere.com |The base URL of the Cohere API. | |meta_fields_to_embed|Optional[List[str]]|None |List of meta fields that should be concatenated with the document content for reranking. | |meta_data_separator |str |\n |Separator used to concatenate the meta fields to the Document content. | |max_tokens_per_doc |int |4096 |The maximum number of tokens to embed for each document defaults to 4096. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|--------------------------------------------------------------| |query |str | |Query string. | |documents|List[Document]| |List of documents to rank. | |top_k |Optional[int] |None |The maximum number of documents you want the Ranker to return.| ## Related Information - [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## CohereTextEmbedder Embed strings using Cohere models. Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Uses Cohere models to embed text strings such as user queries. - Outputs a float vector embedding suitable for use with embedding retrievers. - Supports multiple Cohere embedding models. For a full list, see the [Cohere documentation](https://docs.cohere.com/docs/models#representation). - The embedding model must match the one used by `CohereDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `CohereTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the embedding model to use. Make sure is connected to your Cohere account. For details, see [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx). 2. Set the `input_type` to `search_query` for query pipelines. 4. Go to the **Advanced** tab to configure additional settings such as `truncate`, `timeout`, `embedding_type`, and `api_base_url`. ## Connections `CohereTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever such as `OpenSearchEmbeddingRetriever` or `ElasticsearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/cohere/src/haystack_integrations/components/embedders/cohere/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml CohereTextEmbedder: type: haystack_integrations.components.embedders.cohere.text_embedder.CohereTextEmbedder init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: embed-english-v2.0 input_type: search_query api_base_url: https://api.cohere.com truncate: END timeout: 120 ``` ### Using the Component in a Pipeline This is an example of a query pipeline with `CohereTextEmbedder` that receives a query to embed and then sends the embedded query to `OpenSearchEmbeddingRetriever` to find matching documents. ```yaml # haystack-pipeline components: CohereTextEmbedder: type: haystack_integrations.components.embedders.cohere.text_embedder.CohereTextEmbedder init_parameters: api_key: type: env_var env_vars: - COHERE_API_KEY - CO_API_KEY strict: false model: embed-english-v2.0 input_type: search_query api_base_url: https://api.cohere.com truncate: END timeout: 120 embedding_type: OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: - sender: CohereTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - CohereTextEmbedder.text ``` ## Parameters ### Inputs |Parameter|Type| Description | |---------|----|------------------| |text |str |The text to embed.| ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|---------------------------------------------------------------------------------------------------------------------| |embedding|List[float] | |The embedding of the text.| |meta |Dict[str, Any]| |Metadata about the request.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|------------------------|-----------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var(['COHERE_API_KEY', 'CO_API_KEY'])|The Cohere API key. | |model |str |embed-english-v2.0 |The name of the model to use. Choose a model from the list on the component card. | |input_type |str |search_query |Specifies the type of input you're giving to the model. Supported values are "search_document", "search_query", "classification", and "clustering". Not required for older versions of the embedding models (meaning anything lower than v3), but is required for more recent versions (meaning anything bigger than v2). | |api_base_url |str |https://api.cohere.com |The Cohere API base url. | |truncate |str |END |Truncates embeddings that are too long from start or end, ("NONE"\|"START"\|"END"). Passing "START" discards the start of the input. "END" discards the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model. If "NONE" is selected, when the input exceeds the maximum input token length, an error is returned.| |timeout |int |120 |Request timeout in seconds. | |embedding_type|Optional[EmbeddingTypes]|None |The type of embeddings to return. Defaults to float embeddings. Note that int8, uint8, binary, and ubinary are only valid for v3 models. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |The text to embed.| ## Related Information - [Use Cohere Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-cohere-models.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DeepsetDeepLDocumentTranslator Translate the content of your documents using the DeepL Python SDK. --- :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines. You can replace it with the `DeepLDocumentTranslator` component. ::: ## Key Features - Uses the [DeepL Python library](https://github.com/DeepLcom/deepl-python) to translate document content. - Supports translating one set of documents into multiple target languages at once. - Auto-detects the source language when not specified. - For a list of supported languages, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages). ## Configuration 1. Drag the `DeepsetDeepLDocumentTranslator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the target language code or codes in `target_languages`. For a list of language codes, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages#target-languages). 2. Optionally, set `source_language` to a specific language code, or leave it empty to auto-detect. 3. Connect to your DeepL account on the Integrations page: ::: Once is connected, you can use `DeepsetDeepLDocumentTranslator` without passing the API key in the pipeline YAML. 4. Go to the **Advanced** tab to configure optional settings such as `preserve_formatting`, `formality`, `split_sentences`, `max_retries`, and XML tag handling options. ## Connections `DeepsetDeepLDocumentTranslator` receives a list of documents from converters or retrievers. It outputs translated documents through its `documents` output, which you can send to `PromptBuilder` or use as the pipeline's final document output. ## Usage Examples ### Basic Configuration ```yaml deepl_translator: type: deepset_cloud_custom_nodes.converters.deepl_translator.DeepsetDeepLDocumentTranslator init_parameters: api_key: type: env_var env_vars: - DEEPL_API_KEY strict: false target_languages: - DE preserve_formatting: true include_score: true ``` ### Using the Component in a Pipeline This is an example of a query pipeline where `DeepsetDeepLDocumentTranslator` receives documents from a Ranker and translates them into German. The output of the pipeline are the translated documents. To specify the languages you want DeepL to translate into, you list their codes in the `target_languages` parameter. Here's the pipeline YAML: ```yaml components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/multilingual-e5-base embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: init_parameters: embedding_dim: 768 type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 20 # The number of results to return ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "jeffwan/mmarco-mMiniLMv2-L12-H384-v1" top_k: 20 model_kwargs: torch_dtype: "torch.float16" deepl_translator: type: deepset_cloud_custom_nodes.converters.deepl_translator.DeepsetDeepLDocumentTranslator # For more information about DeepL supported languages, see https://developers.deepl.com/docs/resources/supported-languages init_parameters: api_key: {"type": "env_var", "env_vars": ["DEEPL_API_KEY"], "strict": false} target_languages: ["DE"] # Translate documents into German source_language: # Auto-detects the source language when set to "null" preserve_formatting: true # Prevent automatic correction of formatting include_score: true # Display relevance score connections: # Defines how the components are connected - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: deepl_translator.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "query_embedder.text" - "ranker.query" filters: # These components will receive a potential query filter as input - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "deepl_translator.documents" # The output of the pipeline is the retrieved documents translated into German. max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs |Parameter| Type |Default| Description | |---------|--------------|-------|--------------------------------------------| |documents|List[Document]| |List of Haystack documents to be translated.| ### Outputs |Parameter| Type |Default|Description| |---------|--------------|-------|-----------| |documents|List[Document]| |A list of translated documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-------------------|----------------------------------------------------------------------|------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |target_languages |Union[List[str], str] | |The target language code or a list of target language codes. For a list of target languages, refer to [target languages](https://developers.deepl.com/docs/resources/supported-languages#target-languages). If multiple languages are specified, a translated document is returned for each language. | |source_language |Optional[str] |None |The source language code. If set to `None`, the source language is auto-detected. For a list of source languages, refer to [source languages](https://developers.deepl.com/docs/resources/supported-languages#source-languages). | |api_key |Secret |Secret.from_env_var('DEEPL_API_KEY')|DeepL API key. | |preserve_formatting|Optional[bool] |None |Controls automatic formatting correction. If set to `None`, it acts as `True` to prevent automatic correction of formatting. | |split_sentences |Literal[0, 1, 'nonewlines', None] |None |Controls how the translation engine should split input into sentences before translation. Sets whether the translation engine should first split the input into sentences. This is enabled by default. Possible values are: - 0: 0 means OFF. No splitting at all, whole input is treated as one sentence. Use this option if the input text is already split into sentences, to prevent the engine from splitting the sentence unintentionally. - 1: 1 means ALL. (default) splits on punctuation and on newlines. - 'nonewlines': splits on punctuation only, ignoring newlines. | |context |Optional[str] |None |Makes it possible to include additional context that can influence a translation without being translated itself. Providing additional context can potentially improve translation quality, especially for short, low-context source texts such as product names on an e-commerce website, article headlines on a news website, or UI elements. For more information and examples, refer to the [API documentation](https://developers.deepl.com/docs/api-reference/translate). | |formality |Literal[None, 'less', 'default', 'more', 'prefer_more', 'prefer_less']|None |Controls whether translations should lean toward informal or formal language. This feature currently only works for the following languages DE (German), FR (French), IT (Italian), ES (Spanish), NL (Dutch), PL (Polish), PT-BR and PT-PT (Portuguese), JA (Japanese), and RU (Russian). The available options are: - 'less': Translate using informal language. - 'default': Translate using the default formality. - 'more': Translate using formal language. - 'prefer_more': Translate using formal language if the target language supports formality, otherwise use default formality. - 'prefer_less': Translate using informal language if the target language supports formality, otherwise use default formality.| |max_retries |Optional[int] |5 |Maximum number of network retries after failed HTTP request. Default retries is set to 5. | |glossary |Union[str, None] |None |(Optional) glossary ID to use for translation. Must match specified `source_lang` and `target_lang`. | |tag_handling |Literal[None, 'xml', 'html'] |None |(Optional) Type of tags to parse before translation, only "xml" and "html" are currently available. | |outline_detection |Optional[bool] |None |(Optional) Set to False to disable automatic tag detection. | |non_splitting_tags |Union[str, List[str], None] |None |(Optional) XML tags that should not split a sentence. | |splitting_tags |Union[str, List[str], None] |None |(Optional) XML tags that should split a sentence. | |ignore_tags |Union[str, List[str], None] |None |(Optional) XML tags containing text that should not be translated. | |include_score |bool |True |Whether to include the original document score in the translated document. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|--------------------------------------------| |documents|List[Document]| |List of Haystack documents to be translated.| ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DeepsetDeepLTextTranslator Translate text into the language you choose using the DeepL Python SDK. --- :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines. You can replace it with the `DeepLTextTranslator` component. ::: ## Key Features - Uses the [DeepL Python library](https://github.com/DeepLcom/deepl-python) to translate text strings. - Auto-detects the source language when not specified. - Works with any component that accepts or outputs strings. - For a list of supported languages, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages). ## Configuration 1. Drag the `DeepsetDeepLTextTranslator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the target language code in `target_language`. For a list of codes, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages#target-languages). 2. Optionally, set `source_language` to a specific language code, or leave it empty to auto-detect. 3. Connect to your DeepL account on the Integrations page: Once is connected, you can use `DeepsetDeepLTextTranslator` without passing the API key in the pipeline YAML. 4. Go to the **Advanced** tab to configure optional settings such as `preserve_formatting`, `formality`, `split_sentences`, `max_retries`, and XML tag handling options. ## Connections `DeepsetDeepLTextTranslator` receives a text string as input and outputs the translated text through its `text` output, along with translation metadata through `meta`. It connects to any component that outputs or accepts strings. ## Usage Examples ### Basic Configuration ```yaml DeepsetDeepLTextTranslator: type: deepset_cloud_custom_nodes.converters.deepl_translator.DeepsetDeepLTextTranslator init_parameters: target_language: EN-US api_key: type: env_var env_vars: - DEEPL_API_KEY strict: false ``` ### Using the Component in a Pipeline This query pipeline translates the user query from English to German before retrieval: ```yaml components: translator: type: deepset_cloud_custom_nodes.converters.deepl_translator.DeepsetDeepLTextTranslator init_parameters: target_language: DE api_key: type: env_var env_vars: - DEEPL_API_KEY strict: false retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default top_k: 10 connections: - sender: translator.text receiver: retriever.query inputs: query: - translator.text outputs: documents: retriever.documents translated_query: translator.text max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |Text to translate.| ### Outputs |Parameter| Type |Default|Description| |---------|--------------|-------|-----------| |text |str | |The translated text. | |meta |Dict[str, Any]| |The metadata related to the translation, such as the source and target language. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-------------------|----------------------------------------------------------------------|------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |target_language |str | |The code of the language you want to translate into. For a list of codes, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages#target-languages). | |source_language |Optional[str] |None |The source language code. If `None`, the source language is auto-detected. For a list of codes, see [DeepL documentation](https://developers.deepl.com/docs/resources/supported-languages#source-languages). | |api_key |Secret |Secret.from_env_var('DEEPL_API_KEY')|DeepL API key. | |preserve_formatting|Optional[bool] |None |Controls automatic formatting correction. If ` None`, prevents automatic correction of formatting. | |split_sentences |Literal[0, 1, 'nonewlines', None] |None |Controls how the translation engine should split input into sentences before translation. Sets whether the translation engine should first split the input into sentences. This is enabled by default. Possible values are: - 0: 0 means OFF. No splitting at all, whole input is treated as one sentence. Use this option if the input text is already split into sentences, to prevent the engine from splitting the sentence unintentionally. - 1: 1 means ALL. (default) splits on punctuation and on newlines. - 'nonewlines': splits on punctuation only, ignoring newlines. | |context |Optional[str] |None |Use this setting to include additional context that can influence a translation without being translated itself. Providing additional context can potentially improve translation quality, especially for short, low-context source texts such as product names on an e-commerce website, article headlines on a news website, or UI elements. For more information and examples, refer to the [DeepL API documentation](https://developers.deepl.com/docs/api-reference/translate). | |formality |Literal[None, 'less', 'default', 'more', 'prefer_more', 'prefer_less']|None |Controls whether translations should lean toward informal or formal language. This feature currently only works for the following languages DE (German), FR (French), IT (Italian), ES (Spanish), NL (Dutch), PL (Polish), PT-BR and PT-PT (Portuguese), JA (Japanese), and RU (Russian). The available options are: - 'less': Translate using informal language. - 'default': Translate using the default formality. - 'more': Translate using formal language. - 'prefer_more': Translate using formal language if the target language supports formality, otherwise use default formality. - 'prefer_less': Translate using informal language if the target language supports formality, otherwise use default formality.| |max_retries |Optional[int] |5 |Maximum number of network retries after a failed HTTP request. Default retries is set to 5. | |glossary |Union[str, None] |None |(Optional) glossary ID to use for translation. Must match specified `source_lang` and `target_lang`. | |tag_handling |Literal[None, 'xml', 'html'] |None |(Optional) Type of tags to parse before translation, only "xml" and "html" are currently available. | |outline_detection |Optional[bool] |None |(Optional) Set to False to disable automatic tag detection. | |non_splitting_tags |Union[str, List[str], None] |None |(Optional) XML tags that should not split a sentence. | |splitting_tags |Union[str, List[str], None] |None |(Optional) XML tags that should split a sentence. | |ignore_tags |Union[str, List[str], None] |None |(Optional) XML tags containing text that should not be translated. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |Text to translate.| ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DoclingConverter Convert PDF and other supported files into Markdown documents with Docling. Docling is an open source document processing library. ## Key Features - Wraps the Docling pipeline to convert PDFs and other supported inputs into Markdown content. - Supports OCR, table structure preservation, code block capture, formula recognition, and picture classification. - Extracts Docling metadata, flattens it, and merges it with incoming metadata for downstream filtering and routing. - Inserts a configurable placeholder token at page breaks. - Runs faster with GPU acceleration. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). - For more information about Docling, see the [Docling website](https://www.docling.ai/). :::tip GPU Acceleration `DoclingConverter` runs faster with GPU acceleration. Enable GPU acceleration in the pipeline settings to improve performance: 1. Go to Pipelines and click the pipeline that contains the `DoclingConverter` component. You're redirected to the Pipeline Details page. 2. Go to Settings and click the GPU Acceleration toggle to turn it on. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). ::: ## Configuration 1. Drag the `DoclingConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set `do_ocr` to enable or disable OCR when processing PDF pages (enabled by default). 2. Set `do_table_structure` to preserve table structure during conversion (enabled by default). 4. Go to the **Advanced** tab to configure additional enrichment options such as `do_code_enrichment`, `do_formula_enrichment`, `do_picture_classification`, `do_picture_description`, and advanced overrides like `pipeline_options`, `convert_kwargs`, and `md_export_kwargs`. :::note DOCX files and page numbers When you convert DOCX files, Docling cannot reliably recover page numbers. Run DOCX through a PDF conversion first if your pipeline depends on page numbers. ::: ## Connections `DoclingConverter` receives file paths, Path objects, or ByteStreams through its `sources` input, typically from the `Input` component or `FileTypeRouter`. It outputs a list of Markdown documents through its `documents` output, which you connect to `DocumentSplitter` or `DocumentJoiner` for further processing before writing to a document store. ## Usage Examples ### Basic Configuration ```yaml docling_converter: type: deepset_cloud_custom_nodes.converters.docling_converter.DoclingConverter init_parameters: do_picture_classification: false ``` - Converts PDFs and other supported file types to Markdown content. - Runs OCR and preserves table structure during conversion. - Inserts page break placeholders to maintain document structure. - Extracts and flattens Docling metadata so downstream components can filter by Docling-specific fields. - Accepts file paths, `Path` objects, or `ByteStream` inputs. - For more information about Docling, see the [Docling website](https://www.docling.ai/). ## Configuration 1. Drag the `DoclingConverter` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. ## Connections `DoclingConverter` accepts file paths, `Path` objects, or `ByteStream` inputs as `sources`, and optional metadata as `meta`. It outputs a list of `Document` objects (`documents`). Connect the pipeline's file input to the `sources` input. Connect the `documents` output to `DocumentSplitter`, `DocumentJoiner`, or `DocumentWriter` for further processing. ## Usage Example ### Using the Component in an Index In this example, `DoclingConverter` receives `files` from the `Input` component, then sends the processed documents to `DocumentSplitter`. ```yaml components: docling_converter: type: deepset_cloud_custom_nodes.converters.docling_converter.DoclingConverter init_parameters: do_picture_classification: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: docling-demo max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: SKIP connections: - sender: docling_converter.documents receiver: splitter.documents - sender: splitter.documents receiver: writer.documents inputs: files: - docling_converter.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs |Parameter| Type |Default|Description| |---------|-----------------------------------------------------|-------|-----------| |sources |List[Union[str, Path, ByteStream]] | |File paths, Path objects, or ByteStreams to convert.| |meta |Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]|None |Metadata applied to every generated document or aligned per source.| ### Outputs |Parameter| Type |Default|Description| |---------|--------------|-------|-----------| |documents|List[Document]| |Documents created from the Docling Markdown export.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter |Type |Default|Description| |-----------------------|----------------------------------|-------|-----------| |do_ocr |bool |True |Enable OCR when Docling processes PDF pages.| |do_table_structure |bool |True |Preserve table structure information during conversion.| |do_code_enrichment |bool |False |Enable Docling code OCR to capture code blocks.| |do_formula_enrichment |bool |False |Enable formula OCR to keep math expressions readable.| |do_picture_classification|bool |False |Attach Docling picture classification metadata.| |do_picture_description |bool |False |Add Docling generated picture descriptions to metadata.| |page_break_placeholder |str |"\f" |Token inserted whenever Docling encounters a page break.| |filter_binary_hash |bool |True |Remove Docling `binary_hash` fields from metadata.| |pipeline_options |PdfPipelineOptions \| None |None |Advanced Docling pipeline options for Haystack users. Overrides the individual boolean flags.| |convert_kwargs |Dict[str, Any] \| None |None |Additional arguments forwarded to `DocumentConverter.convert()`, such as `headers` or `max_num_pages`.| |md_export_kwargs |Dict[str, Any] \| None |None |Overrides for Docling Markdown export, for example `image_placeholder` or custom formatting flags.| ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default|Description| |---------|-----------------------------------------------------|-------|-----------| |sources |List[Union[str, Path, ByteStream]] | |Paths or ByteStreams for the files you want to convert.| |meta |Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]|None |Metadata applied to every generated document or aligned per source list.| ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) - [GPU Acceleration](/docs/enable-gpu-acceleration) --- ## ElasticsearchBM25Retriever Retrieve documents from the `ElasticsearchDocumentStore` using the BM25 algorithm to find keywords matching the user's query. ## Key Features - Keyword-based retrieval using the BM25 algorithm. - Only compatible with `ElasticsearchDocumentStore`. - Calculates weighted word overlap between the query and documents. - Works well for exact keyword matching, product codes, and proper names. - Lightweight and performs well on out-of-domain data. - Can be combined with `ElasticsearchEmbeddingRetriever` and `DocumentJoiner` for hybrid retrieval. ## Configuration 1. Drag the `ElasticsearchBM25Retriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Configure the `document_store` connection with your Elasticsearch hosts and index name. 2. Set `top_k` to the maximum number of documents to return. 4. Go to the **Advanced** tab to configure `filters`, `fuzziness`, `scale_score`, and `filter_policy`. ## Connections `ElasticsearchBM25Retriever` receives a query string from the `Input` component. It outputs a list of matching documents through its `documents` output. You can connect its output to a ranker or `DocumentJoiner` for hybrid retrieval with `ElasticsearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`bm25_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/elasticsearch/src/haystack_integrations/components/retrievers/elasticsearch/bm25_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ElasticsearchBM25Retriever: type: haystack_integrations.components.retrievers.elasticsearch.bm25_retriever.ElasticsearchBM25Retriever init_parameters: fuzziness: AUTO top_k: 10 scale_score: false filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: index: my_index embedding_similarity_function: cosine ``` ### Using the Component in a Pipeline This is an example of a document search pipeline that combines keyword-based retrieval with embedding-based retrieval. It uses `ElasticsearchBM25Retriever` and `ElasticsearchEmbeddingRetriever` to retrieve documents from the document store. It then joins the results of the two with a `DocumentJoiner`. ```yaml # haystack-pipeline components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: "intfloat/simlm-msmarco-reranker" top_k: 20 ElasticsearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.elasticsearch.embedding_retriever.ElasticsearchEmbeddingRetriever init_parameters: filters: top_k: 10 num_candidates: filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: hosts: custom_mapping: index: 'my_index' embedding_similarity_function: cosine ElasticsearchBM25Retriever: type: haystack_integrations.components.retrievers.elasticsearch.bm25_retriever.ElasticsearchBM25Retriever init_parameters: filters: fuzziness: AUTO top_k: 10 scale_score: false filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: hosts: custom_mapping: index: 'my_index' embedding_similarity_function: cosine connections: # Defines how the components are connected - sender: document_joiner.documents receiver: ranker.documents - sender: query_embedder.embedding receiver: ElasticsearchEmbeddingRetriever.query_embedding - sender: ElasticsearchEmbeddingRetriever.documents receiver: document_joiner.documents - sender: ElasticsearchBM25Retriever.documents receiver: document_joiner.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "query_embedder.text" - "ranker.query" - ElasticsearchBM25Retriever.query filters: # These components will receive a potential query filter as input - "ElasticsearchEmbeddingRetriever.filters" - "ElasticsearchBM25Retriever.filters" outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs |Parameter| Type |Default| Description | |---------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query |str | |String to search in the document text. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. For details, check the Init Parameters section.| |top_k |Optional[int] |None |Maximum number of documents to return. | ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|----------------------------------------------------------------------------------------------| |documents|List[Document]| |List of documents that match the query.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|--------------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store|ElasticsearchDocumentStore| |An instance of ElasticsearchDocumentStore to retrieve documents from. | |filters |Optional[Dict[str, Any]] |None |Filters applied to the retrieved documents. | |fuzziness |str |AUTO |Fuzziness parameter passed to Elasticsearch. For details, see [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness).| |top_k |int |10 |Maximum number of documents to return. | |scale_score |bool |False |If `True` scales the Document`s scores between 0 and 1. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied. Possible options: - `REPLACE` (default): Overrides the initialization filters with the filters specified at runtime. Use this policy to dynamically change filtering for specific queries. - `MERGE`: Combines runtime filters with initialization filters to narrow down the search. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query |str | |String to search in the `Document`s text. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved documents. The way runtime filters are applied depends on the `filter_policy` chosen.| |top_k |Optional[int] |None |Maximum number of `Document` to return. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ElasticsearchEmbeddingRetriever Retrieve documents from the `ElasticsearchDocumentStore` based on their semantic similarity to the query. ## Key Features - Semantic similarity-based retrieval using approximate kNN search. - Only compatible with `ElasticsearchDocumentStore`. - Compares query embeddings to document embeddings to find the most relevant results. - Requires a text embedder before it in the pipeline, and the embedding model must match the one used in the indexing pipeline. - Can be combined with `ElasticsearchBM25Retriever` and `DocumentJoiner` for hybrid retrieval. ## Configuration 1. Drag the `ElasticsearchEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Configure the `document_store` connection with your Elasticsearch hosts and index name. 2. Set `top_k` to the maximum number of documents to return. 4. Go to the **Advanced** tab to configure `filters`, `num_candidates`, and `filter_policy`. ## Connections `ElasticsearchEmbeddingRetriever` receives a query embedding (a list of floats) from a text embedder such as `DeepsetNvidiaTextEmbedder`. It outputs a list of semantically similar documents through its `documents` output. You can connect its output to a ranker or `DocumentJoiner` for hybrid retrieval with `ElasticsearchBM25Retriever`. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/elasticsearch/src/haystack_integrations/components/retrievers/elasticsearch/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ElasticsearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.elasticsearch.embedding_retriever.ElasticsearchEmbeddingRetriever init_parameters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: index: my_index embedding_similarity_function: cosine ``` ### Using the Component in a Pipeline This is an example of a document search pipeline that uses `ElasticsearchEmbeddingRetriever` combined with `ElasticsearchBM25Retriever` and then joins the results with a `DocumentJoiner`. ```yaml # haystack-pipeline components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: "intfloat/simlm-msmarco-reranker" top_k: 20 ElasticsearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.elasticsearch.embedding_retriever.ElasticsearchEmbeddingRetriever init_parameters: filters: top_k: 10 num_candidates: filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: hosts: custom_mapping: index: 'my_index' embedding_similarity_function: cosine ElasticsearchBM25Retriever: type: haystack_integrations.components.retrievers.elasticsearch.bm25_retriever.ElasticsearchBM25Retriever init_parameters: filters: fuzziness: AUTO top_k: 10 scale_score: false filter_policy: replace document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: hosts: custom_mapping: index: 'my_index' embedding_similarity_function: cosine connections: # Defines how the components are connected - sender: document_joiner.documents receiver: ranker.documents - sender: query_embedder.embedding receiver: ElasticsearchEmbeddingRetriever.query_embedding - sender: ElasticsearchEmbeddingRetriever.documents receiver: document_joiner.documents - sender: ElasticsearchBM25Retriever.documents receiver: document_joiner.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "query_embedder.text" - "ranker.query" - ElasticsearchBM25Retriever.query filters: # These components will receive a potential query filter as input - "ElasticsearchEmbeddingRetriever.filters" - "ElasticsearchBM25Retriever.filters" outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type |Default| Description | |---------------|------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding|List[float] | |Embedding of the query. | |filters |Optional[Dict[str, Any]]|None |Filters applied when fetching documents from the Document Store. Filters are applied during the approximate kNN search to ensure the Retriever returns `top_k` matching documents. The way runtime filters are applied depends on the `filter_policy` selected when configuring the Retriever.| |top_k |Optional[int] |None |Maximum number of documents to return. | ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|--------------------------------------------------------------------------------------------------------------------| |documents|List[Document]| |List of documents most similar to the given `query_embedding`.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|--------------------------|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store|ElasticsearchDocumentStore| |The Elasticsearch document store to retrieve documents from. | |filters |Optional[Dict[str, Any]] |None |Filters applied to the retrieved Documents. Filters are applied during the approximate KNN search to ensure that top_k matching documents are returned. | |top_k |int | 10|Maximum number of Documents to return. | |num_candidates|Optional[int] |None |Number of approximate nearest neighbor candidates on each shard. Defaults to top_k * 10. Increasing this value improves search accuracy at the cost of slower search speeds. You can read more about it in the Elasticsearch [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)| |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied. Possible options: - `REPLACE` (default): Overrides the initialization filters with the filters specified at runtime. Use this policy to dynamically change filtering for specific queries. - `MERGE`: Combines runtime filters with initialization filters to narrow down the search. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding|List[float] | |Embedding of the query. | |filters |Optional[Dict[str, Any]]|None |Filters applied when fetching documents from the Document Store. Filters are applied during the approximate kNN search to ensure the Retriever returns `top_k` matching documents. The way runtime filters are applied depends on the `filter_policy` selected when initializing the Retriever.| |top_k |Optional[int] |None |Maximum number of documents to return. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## ElasticsearchHybridRetriever Retrieve documents from an `ElasticsearchDocumentStore` using a combination of BM25 keyword search and dense vector similarity search. ## Key Features - Hybrid retrieval that combines BM25 keyword search with embedding-based vector search. - Uses Reciprocal Rank Fusion (RRF) by default to merge results from both search methods. - Configurable join modes for result merging. - Built-in text embedder for automatic query embedding. - Separate `top_k` and filter settings for BM25 and embedding sub-retrievers. ## Configuration 1. Drag the `ElasticsearchHybridRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `ElasticsearchDocumentStore` with your Elasticsearch instance details. - Set the `embedder` to the text embedder for query embedding. - Set `top_k` to control the final number of documents to return. 4. Go to the **Advanced** tab to configure `top_k_bm25`, `top_k_embedding`, `fuzziness`, `join_mode`, and filter policies. ## Connections `ElasticsearchHybridRetriever` receives the user query as a text string, typically from the `Input` component. It outputs a merged list of documents combining keyword and semantic search results. ## Source Code To check this component's source code, open [`elasticsearch_hybrid_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/elasticsearch/src/haystack_integrations/components/retrievers/elasticsearch/elasticsearch_hybrid_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml ElasticsearchHybridRetriever: type: haystack_integrations.components.retrievers.elasticsearch.elasticsearch_hybrid_retriever.ElasticsearchHybridRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.elasticsearch.document_store.ElasticsearchDocumentStore init_parameters: hosts: - http://localhost:9200 index: my-index embedder: type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder init_parameters: model: text-embedding-3-small ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query for both keyword and embedding-based search. | | `filters_bm25` | Optional[Dict[str, Any]] | Filters to apply to the BM25 keyword retriever. | | `filters_embedding` | Optional[Dict[str, Any]] | Filters to apply to the embedding retriever. | | `top_k_bm25` | Optional[int] | The maximum number of documents from the BM25 retriever. | | `top_k_embedding` | Optional[int] | The maximum number of documents from the embedding retriever. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The merged and reranked retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | ElasticsearchDocumentStore | | An instance of `ElasticsearchDocumentStore`. | | `embedder` | TextEmbedder | *(required)* | A text embedder component for converting the query to a vector. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Default filters for the BM25 sub-retriever. | | `fuzziness` | str | `"AUTO"` | Fuzziness setting for BM25 keyword matching. | | `top_k_bm25` | int | 10 | Maximum number of results from the BM25 retriever. | | `scale_score` | bool | False | Whether to scale BM25 scores to the 0-1 range. | | `filter_policy_bm25` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Filter policy for the BM25 sub-retriever. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Default filters for the embedding sub-retriever. | | `top_k_embedding` | int | 10 | Maximum number of results from the embedding retriever. | | `num_candidates` | Optional[int] | None | The number of candidates to consider before final ranking for embedding retrieval. | | `filter_policy_embedding` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Filter policy for the embedding sub-retriever. | | `join_mode` | Union[str, JoinMode] | `JoinMode.RECIPROCAL_RANK_FUSION` | The method for merging results from both retrievers. | | `weights` | Optional[List[float]] | None | Weights for each retriever when using weighted join modes. | | `top_k` | Optional[int] | None | Maximum number of documents to return after merging. | | `sort_by_score` | bool | True | Whether to sort merged results by score. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query for both retrieval methods. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Filters to apply at query time for the BM25 retriever. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Filters to apply at query time for the embedding retriever. | | `top_k_bm25` | Optional[int] | None | Override the init-time `top_k_bm25` setting. | | `top_k_embedding` | Optional[int] | None | Override the init-time `top_k_embedding` setting. | ## Related Information - [ElasticsearchBM25Retriever](/docs/reference/pipeline-components/integrations/elasticsearch/ElasticsearchBM25Retriever.mdx) - [ElasticsearchEmbeddingRetriever](/docs/reference/pipeline-components/integrations/elasticsearch/ElasticsearchEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## FAISSDocumentStore Store and retrieve documents using [FAISS](https://faiss.ai/) (Facebook AI Similarity Search), a library for efficient vector similarity search. FAISSDocumentStore is suitable for small to medium-sized datasets where simplicity is preferred over distributed scalability. ## Key Features - Stores document metadata in a local JSON file and embeddings in a FAISS index. - Supports a wide range of FAISS index types (for example, `Flat`, `IVFFlat`, `HNSW`). - Simple persistence: saves the FAISS index to a `.faiss` file and documents to a `.json` file. - No external database required — runs entirely in memory backed by local files. ## Configuration 1. Drag the `FAISSDocumentStore` component onto the canvas from the Component Library. 2. Configure the `embedding_dim` to match your embedding model's output dimension. 3. Optionally set `index_path` to an existing `.faiss` index file to load a pre-built index. 4. Set `index_string` to choose the FAISS index type (for example, `Flat` for exact search or `IVFFlat` for approximate search on larger datasets). ## Source Code To check this component's source code, open [`document_store.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/faiss/src/haystack_integrations/document_stores/faiss/document_store.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FAISSDocumentStore: type: haystack_integrations.document_stores.faiss.document_store.FAISSDocumentStore init_parameters: embedding_dim: 384 index_string: Flat ``` ### Loading an Existing Index ```yaml FAISSDocumentStore: type: haystack_integrations.document_stores.faiss.document_store.FAISSDocumentStore init_parameters: index_path: /path/to/my_index.faiss embedding_dim: 384 ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `index_path` | Optional[str] | None | Path to an existing `.faiss` index file to load. If None, creates a new index. | | `index_string` | str | `Flat` | The FAISS index type string. Use `Flat` for exact search, `IVFFlat` or `HNSW` for approximate nearest neighbor search on larger datasets. | | `embedding_dim` | int | `768` | The dimensionality of document embeddings. Must match your embedding model's output. | ## Related Information - [FAISSEmbeddingRetriever](/docs/reference/pipeline-components/integrations/faiss/FAISSEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## FAISSEmbeddingRetriever Retrieve documents from a `FAISSDocumentStore` using vector similarity search. Use this component in query pipelines to find semantically similar documents based on dense embeddings with efficient FAISS indexing. ## Key Features - Performs vector similarity search using FAISS for fast retrieval. - Works with all FAISS index types supported by `FAISSDocumentStore`. - Configurable filter policy to merge or replace filters at query time. - Supports async execution via `run_async`. ## Configuration 1. First, configure a `FAISSDocumentStore` in your pipeline. 2. Drag the `FAISSEmbeddingRetriever` component onto the canvas from the Component Library. 3. Connect an embedder component to provide `query_embedding` as input. 4. Connect the retriever output to downstream components such as `PromptBuilder`. ## Connections `FAISSEmbeddingRetriever` receives a `query_embedding` (list of floats) from a text embedder such as `SentenceTransformersTextEmbedder`. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/faiss/src/haystack_integrations/components/retrievers/faiss/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FAISSEmbeddingRetriever: type: haystack_integrations.components.retrievers.faiss.embedding_retriever.FAISSEmbeddingRetriever init_parameters: document_store: FAISSDocumentStore top_k: 5 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 document_store: type: haystack_integrations.document_stores.faiss.document_store.FAISSDocumentStore init_parameters: embedding_dim: 384 index_string: Flat retriever: type: haystack_integrations.components.retrievers.faiss.embedding_retriever.FAISSEmbeddingRetriever init_parameters: document_store: document_store top_k: 5 connections: - sender: text_embedder.embedding receiver: retriever.query_embedding inputs: query: - text_embedder.text outputs: documents: retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The query embedding vector to search for similar documents. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of the most similar documents from the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | FAISSDocumentStore | | The FAISS document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding vector to search with. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | ## Related Information - [FAISSDocumentStore](/docs/reference/pipeline-components/integrations/faiss/FAISSDocumentStore.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## FastembedDocumentEmbedder Compute embeddings for a list of documents using [Fastembed](https://github.com/qdrant/fastembed) embedding models. Use this component in indexing pipelines to prepare documents for embedding-based retrieval. ## Key Features - Uses CPU-optimized embedding models from the [Fastembed library](https://qdrant.github.io/fastembed/). - Fast and lightweight — designed for production use without GPU requirements. - Stores the computed embedding in each document's `embedding` field. - Supports adding metadata fields to the text before embedding. - Configurable batch size for efficient processing. ## Configuration 1. Drag the `FastembedDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Fastembed model you want to use (for example, `BAAI/bge-small-en-v1.5`). For a list of supported models, see the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). 4. Go to the **Advanced** tab to configure `batch_size`, `meta_fields_to_embed`, `embedding_separator`, `prefix`, and `suffix`. ## Connections `FastembedDocumentEmbedder` receives a list of documents, typically from a document splitter or converter. It outputs the same documents with embeddings added to their `embedding` field, ready to be sent to a `DocumentWriter`. ## Source Code To check this component's source code, open [`fastembed_document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FastembedDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.FastembedDocumentEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 batch_size: 256 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: FastembedDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.FastembedDocumentEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 batch_size: 256 meta_fields_to_embed: embedding_separator: "\n" document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore init_parameters: url: http://localhost:6333 index: documents connections: - sender: FastembedDocumentEmbedder.documents receiver: document_writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents with their `embedding` field populated. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `BAAI/bge-small-en-v1.5` | The name of the Fastembed model to use. For a full list, see the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). | | `cache_dir` | Optional[str] | None | The directory to cache downloaded models. | | `threads` | Optional[int] | None | The number of threads for model inference. | | `prefix` | str | `""` | A string to add at the beginning of each document's text before embedding. | | `suffix` | str | `""` | A string to add at the end of each document's text before embedding. | | `batch_size` | int | 256 | The number of documents to process in each batch. | | `progress_bar` | bool | True | Whether to show a progress bar during embedding. | | `parallel` | Optional[int] | None | The number of parallel processes for batch processing. | | `local_files_only` | bool | False | Whether to use only locally cached models. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text before embedding. | | `embedding_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## FastembedRanker Rank documents by their similarity to a query using [Fastembed](https://github.com/qdrant/fastembed) cross-encoder models. ## Key Features - Reranks documents based on semantic similarity to the query using cross-encoder models. - Uses CPU-optimized models from the [Fastembed library](https://qdrant.github.io/fastembed/). - Returns documents sorted from most to least relevant. - Configurable number of results with `top_k`. - Supports optional score threshold to filter out low-quality results. - Can include metadata fields in the document text for ranking. ## Configuration 1. Drag the `FastembedRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model_name` to the Fastembed cross-encoder model to use (for example, `Xenova/ms-marco-MiniLM-L-6-v2`). For supported models, see the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). 2. Set `top_k` to limit the number of documents returned. 4. Go to the **Advanced** tab to configure `score_threshold`, `meta_fields_to_embed`, and `batch_size`. ## Connections `FastembedRanker` receives a query string and a list of documents from a retriever. It outputs a reranked list of documents, sorted by relevance to the query. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/rankers/fastembed/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FastembedRanker: type: haystack_integrations.components.rankers.fastembed.FastembedRanker init_parameters: model_name: Xenova/ms-marco-MiniLM-L-6-v2 top_k: 5 batch_size: 64 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantEmbeddingRetriever init_parameters: top_k: 20 document_store: type: haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore init_parameters: url: http://localhost:6333 index: documents FastembedRanker: type: haystack_integrations.components.rankers.fastembed.FastembedRanker init_parameters: model_name: Xenova/ms-marco-MiniLM-L-6-v2 top_k: 5 connections: - sender: retriever.documents receiver: FastembedRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - FastembedRanker.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query to rank documents against. | | `documents` | List[Document] | A list of documents to rerank. | | `top_k` | Optional[int] | The maximum number of documents to return. Overrides the init-time `top_k`. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The reranked documents, sorted from most to least relevant. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model_name` | str | `Xenova/ms-marco-MiniLM-L-6-v2` | The name of the Fastembed cross-encoder model to use. | | `top_k` | int | 10 | The maximum number of documents to return. | | `cache_dir` | Optional[str] | None | The directory to cache downloaded models. | | `threads` | Optional[int] | None | The number of threads for model inference. | | `batch_size` | int | 64 | The number of document pairs to score in each batch. | | `parallel` | Optional[int] | None | The number of parallel processes for batch processing. | | `local_files_only` | bool | False | Whether to use only locally cached models. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text when scoring. | | `meta_data_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | | `score_threshold` | Optional[float] | None | A minimum score threshold. Documents below this score are filtered out. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query to rank documents against. | | `documents` | List[Document] | | A list of documents to rerank. | | `top_k` | Optional[int] | None | The maximum number of documents to return. Overrides the init-time `top_k`. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## FastembedTextEmbedder Embed strings using [Fastembed](https://github.com/qdrant/fastembed) embedding models. Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Uses CPU-optimized embedding models from the [Fastembed library](https://qdrant.github.io/fastembed/). - Fast and lightweight — designed for production use without GPU requirements. - Supports a wide range of models from BAAI, Xenova, and others. - The embedding model must match the one used by `FastembedDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `FastembedTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Fastembed model you want to use (for example, `BAAI/bge-small-en-v1.5`). For a list of supported models, see the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `cache_dir`, and `threads`. ## Connections `FastembedTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever. ## Source Code To check this component's source code, open [`fastembed_text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FastembedTextEmbedder: type: haystack_integrations.components.embedders.fastembed.FastembedTextEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 prefix: "" suffix: "" progress_bar: true ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: FastembedTextEmbedder: type: haystack_integrations.components.embedders.fastembed.FastembedTextEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 QdrantEmbeddingRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore init_parameters: url: http://localhost:6333 index: documents connections: - sender: FastembedTextEmbedder.embedding receiver: QdrantEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - FastembedTextEmbedder.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `BAAI/bge-small-en-v1.5` | The name of the Fastembed model to use. For a full list, see the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). | | `cache_dir` | Optional[str] | None | The directory to cache downloaded models. Defaults to the system cache directory. | | `threads` | Optional[int] | None | The number of threads for model inference. If not set, uses the available CPU count. | | `prefix` | str | `""` | A string to add at the beginning of the text before embedding. | | `suffix` | str | `""` | A string to add at the end of the text before embedding. | | `progress_bar` | bool | True | Whether to show a progress bar during model loading. | | `parallel` | Optional[int] | None | The number of parallel processes for batch processing. | | `local_files_only` | bool | False | Whether to use only locally cached models, without downloading from the internet. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## DeepsetFirecrawlWebScraper Use the Firecrawl service to crawl websites and return the crawled documents. ## Key Features - Crawls websites using the paid [Firecrawl](https://www.firecrawl.dev/) service. - Returns crawled content in Markdown format, optimized for use with LLMs. - Accepts URLs from a CSV file processed through `DeepsetCSVRowsToDocumentsConverter` and `OutputAdapter`. :::info Page Crawl limits When using this component, set a page crawl limit using the `limit` parameter. Without a limit, Firecrawl crawls all subpages, which can result in high charges. ::: ## Configuration 1. Drag the `DeepsetFirecrawlWebScraper` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set your Firecrawl API key. Add `FIRECRAWL_API_KEY` as a secret in . For more information, see [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Configure `params` with at least a `limit` value to cap the number of pages crawled. For a full list of accepted parameters, see the [Firecrawl crawl-post endpoint](https://docs.firecrawl.dev/api-reference/endpoint/crawl-post) documentation. 4. Go to the **Advanced** tab to configure additional crawl parameters. ### Passing the URLs `DeepsetFirecrawlWebScraper` needs to receive URLs to crawl in a CSV file. The file must contain a column called `urls` where each row contains a URL to crawl. Structure your indexing pipeline as follows: 1. Start with `DeepsetCSVRowsToDocumentsConverter`. It converts each row in a CSV file into a document object. 2. Connect `DeepsetCSVRowsToDocumentsConverter` to `OutputAdapter` with its template set to turn a list of documents into a list of strings. This is an example template you can use: ```yaml OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: |- {% set ns = namespace(str_list=[]) %} {% for document in documents %} {% set _ = ns.str_list.append(document.content) %} {% endfor %} {{ ns.str_list }} ``` 3. Send the resulting list of strings to `DeepsetFirecrawlWebScraper`. ## Connections `DeepsetFirecrawlWebScraper` receives a list of URL strings from `OutputAdapter`. It outputs a list of documents containing the scraped content through its `documents` output, which you connect to `DocumentWriter` to write them into a document store. ## Usage Examples ### Basic Configuration ```yaml DeepsetFirecrawlWebScraper: type: deepset_cloud_custom_nodes.crawler.firecrawl.DeepsetFirecrawlWebScraper init_parameters: api_key: type: env_var env_vars: - FIRECRAWL_API_KEY strict: false ``` ### Using the Component in a Pipeline This example shows an index that scrapes content from websites using Firecrawl, converts it into documents, and writes them to an OpenSearch document store for access by the query pipeline. The index starts with a CSV file containing the URLs to crawl. This file is sent to `DeepsetCSVRowsToDocumentsConverter`, which converts each row into a document and sends it to `OutputAdapter`. Using a Jinja2 template, `OutputAdapter` transforms these documents into a list of strings that `DeepsetFirecrawlWebScraper` can process. `DeepsetFirecrawlWebScraper` then scrapes content from each URL, converts it into documents, and sends them to `DocumentWriter`, which writes the documents to the OpenSearch store. ```yaml # haystack-pipeline components: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: |- {% set ns = namespace(str_list=[]) %} {% for document in documents %} {% set _ = ns.str_list.append(document.content) %} {% endfor %} {{ ns.str_list }} output_type: typing.List[str] DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 similarity: cosine policy: NONE DeepsetCSVRowsToDocumentsConverter: type: deepset_cloud_custom_nodes.converters.csv_rows_to_documents.DeepsetCSVRowsToDocumentsConverter init_parameters: content_column: urls encoding: utf-8 DeepsetFirecrawlWebScraper: type: deepset_cloud_custom_nodes.crawler.firecrawl.DeepsetFirecrawlWebScraper init_parameters: params: null connections: # Defines how the components are connected - sender: DeepsetCSVRowsToDocumentsConverter.documents receiver: OutputAdapter.documents - sender: OutputAdapter.output receiver: DeepsetFirecrawlWebScraper.urls - sender: DeepsetFirecrawlWebScraper.documents receiver: DocumentWriter.documents max_loops_allowed: 100 metadata: {} inputs: files: DeepsetCSVRowsToDocumentsConverter.sources ``` ## Parameters ### Inputs |Parameter| Type |Default| Description | |---------|-----------|-------|---------------------------------| |urls |List[str] | |URLs of the websites to crawl. | |params |Dict \| None|None |Parameters for the crawl request.| ### Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|-------------------------------------------------| |documents|List[Document]| |List of Documents containing the crawled content.| ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter| Type | Default | Description | |---------|-----------|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |params |Dict \| None| |For a list of accepted parameters, see the Body section of the [crawl-post endpoint](https://docs.firecrawl.dev/api-reference/endpoint/crawl-post) documentation. It's important to set the `limit` parameter defining the maximum number of pages to crawl. Otherwise, Firecrawl crawls all subpages, which results in high charges.| |api_key |Secret |Secret.from_env_var('FIRECRAWL_API_KEY')|API key for Firecrawl. If not provided, it's read from the `FIRECRAWL_API_KEY` environment variable. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|-----------|-------|---------------------------------| |urls |List[str] | |URLs of the websites to crawl. | |params |Dict \| None|None |Parameters for the crawl request.| ## Related Information - [Add Secrets to Connect to Third Party Providers](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## GoogleAIGeminiChatGenerator Complete chats using Gemini models through Google AI Studio. :::info Deprecation Notice `GoogleAIGeminiChatGenerator` will be deprecated after August 2025. Switch to the new `GoogleGenAIChatGenerator` instead. ::: ## Key Features - Chat completion using Gemini models through Google AI Studio - Streaming support for real-time token-by-token responses - Tool/function calling support - Configurable safety settings for content filtering - Configurable generation parameters such as temperature and top_p ## Configuration 1. Drag the `GoogleAIGeminiChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your Google AI Studio API key. You need to connect to your Google AI Studio account first. For details, see [Use Google Gemini Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx). 2. Select a model. For available models, see [Google documentation](https://ai.google.dev/gemini-api/docs/models/gemini). 4. Go to the **Advanced** tab to configure generation settings, safety settings, tools, and streaming. ## Connections `GoogleAIGeminiChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`gemini.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_ai/src/haystack_integrations/components/generators/google_ai/chat/gemini.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml GoogleAIGeminiChatGenerator: type: haystack_integrations.components.generators.google_ai.chat.gemini.GoogleAIGeminiChatGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY strict: false model: gemini-1.5-flash ``` ### Using the Component in a Pipeline This is an example RAG pipeline with `GoogleAIGeminiChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false GoogleAIGeminiChatGenerator: type: haystack_integrations.components.generators.google_ai.chat.gemini.GoogleAIGeminiChatGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY strict: false model: gemini-1.5-flash generation_config: safety_settings: tools: tool_config: streaming_callback: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: GoogleAIGeminiChatGenerator.messages - sender: GoogleAIGeminiChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :------------------------------------------------------------------ | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------------- | :----------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var('GOOGLE_API_KEY') | Google AI Studio API key. To get a key, see [Google AI Studio](https://aistudio.google.com/). | | `model` | str | gemini-1.5-flash | Name of the model to use. For available models, see [Google documentation](https://ai.google.dev/gemini-api/docs/models/gemini). | | `generation_config` | Optional[Union[GenerationConfig, Dict[str, Any]]] | None | The generation configuration to use. This can be a `GenerationConfig` object or a dictionary of parameters. For available parameters, see [the API reference](https://ai.google.dev/api/generate-content). | | `safety_settings` | Optional[Dict[HarmCategory, HarmBlockThreshold]] | None | The safety settings to use. A dictionary with `HarmCategory` as keys and `HarmBlockThreshold` as values. For more information, see [the API reference](https://ai.google.dev/api/generate-content). | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. | | `tool_config` | Optional[content_types.ToolConfigDict] | None | The tool config to use. See the documentation for [ToolConfig](https://ai.google.dev/api/caching#ToolConfig). | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. | ## Related Information - [Use Google Gemini Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## GoogleAIGeminiGenerator Generate text using multimodal Gemini models through Google AI Studio. :::warning Deprecation Notice This integration will be deprecated soon. We recommend using `GoogleGenAIChatGenerator` instead, which provides unified access to both Gemini Developer API and Vertex AI. ::: ## Key Features - Text generation using multimodal Gemini models through Google AI Studio - Supports both text and image inputs for vision-based tasks - Streaming support for real-time token-by-token responses - Designed for text generation tasks, not for chat (use `GoogleGenAIChatGenerator` for chat) ## Configuration 1. Drag the `GoogleAIGeminiGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your Google AI Studio API key. Get your API key from [Google AI Studio](https://aistudio.google.com/app/apikey). For detailed instructions, see [Use Google AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx). 2. Select a model. For available models, see [Google AI models](https://ai.google.dev/gemini-api/docs/models/gemini). 4. Go to the **Advanced** tab to configure generation settings, safety settings, and streaming. ## Connections `GoogleAIGeminiGenerator` accepts multimodal inputs through its `parts` input — a list of strings, `ByteStream` objects, or `Part` objects. It outputs generated text as `replies` (a list of strings). Connect `PromptBuilder`'s `prompt` output to this component's `parts` input. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`gemini.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_ai/src/haystack_integrations/components/generators/google_ai/gemini.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml GoogleAIGeminiGenerator: type: haystack_integrations.components.generators.google_ai.gemini.GoogleAIGeminiGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY strict: false model: gemini-2.0-flash ``` Typically, you connect `PromptBuilder` to the `parts` input and `AnswerBuilder` to the `replies` output. This component is designed for text generation, not chat. For chat capabilities, use `GoogleGenAIChatGenerator` instead. This query pipeline uses `GoogleAIGeminiGenerator` to generate text responses: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 fuzziness: 0 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }} required_variables: variables: GoogleAIGeminiGenerator: type: haystack_integrations.components.generators.google_ai.gemini.GoogleAIGeminiGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY strict: false model: gemini-2.0-flash generation_config: safety_settings: streaming_callback: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: bm25_retriever.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: GoogleAIGeminiGenerator.parts - sender: GoogleAIGeminiGenerator.replies receiver: AnswerBuilder.replies - sender: bm25_retriever.documents receiver: AnswerBuilder.documents inputs: query: - bm25_retriever.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :------------------------------------------- | :------ | :----------------------------------------------------------------------- | | `parts` | Variadic[Union[str, ByteStream, Part]] | | A heterogeneous list of strings, `ByteStream` or `Part` objects. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ### Outputs | Parameter | Type | Description | | :-------- | :--------- | :--------------------------------------------- | | `replies` | List[str] | A list of strings containing the generated responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------------- | :------------------------------------ | :----------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var('GOOGLE_API_KEY') | Google AI Studio API key. | | `model` | str | gemini-2.0-flash | Name of the model to use. For available models, see [Google AI models](https://ai.google.dev/gemini-api/docs/models/gemini). | | `generation_config` | Optional[Union[GenerationConfig, Dict[str, Any]]] | None | The generation configuration to use. Can be a `GenerationConfig` object or a dictionary of parameters. | | `safety_settings` | Optional[Dict[HarmCategory, HarmBlockThreshold]] | None | The safety settings to use. A dictionary with `HarmCategory` as keys and `HarmBlockThreshold` as values. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------- | :------ | :----------------------------------------------------------------------- | | `parts` | Variadic[Union[str, ByteStream, Part]] | | A heterogeneous list of strings, `ByteStream` or `Part` objects. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ## Related Information - [Use Google AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx) - [GoogleGenAIChatGenerator](/docs/reference/pipeline-components/integrations/google-ai/GoogleGenAIChatGenerator.mdx) --- ## GoogleGenAIChatGenerator Complete chats using Google's Gemini models through the Google Gen AI SDK. ## Key Features - Unified interface for both the Gemini Developer API and Vertex AI - Supports Gemini 2.0 Flash and other Gemini model variants - Streaming support for real-time token-by-token responses - Tool/function calling support - Configurable generation parameters such as temperature and max_tokens - Configurable safety settings for content filtering ## Configuration 1. Drag the `GoogleGenAIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Choose the API to use: `gemini` for the Gemini Developer API or `vertex` for Vertex AI. 2. For the Gemini Developer API, enter your Google API key. Get your API key from [Google AI Studio](https://aistudio.google.com/app/apikey). For Vertex AI, enter your GCP project ID and location instead. 3. Select a model (for example, `gemini-2.0-flash`). For details, see [Use Google Gemini Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx). 4. Go to the **Advanced** tab to configure generation parameters, safety settings, tools, and streaming. ## Connections `GoogleGenAIChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_genai/src/haystack_integrations/components/generators/google_genai/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml GoogleGenAIChatGenerator: type: haystack_integrations.components.generators.google_genai.chat.chat_generator.GoogleGenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini model: gemini-2.0-flash ``` ### Using the Component in a Pipeline This is an example RAG pipeline with `GoogleGenAIChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false GoogleGenAIChatGenerator: type: haystack_integrations.components.generators.google_genai.chat.chat_generator.GoogleGenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini model: gemini-2.0-flash generation_kwargs: safety_settings: streaming_callback: tools: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: GoogleGenAIChatGenerator.messages - sender: GoogleGenAIChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the model. | | `safety_settings` | Optional[List[Dict[str, Any]]] | None | Safety settings for content filtering. If provided, overrides the default settings. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of Tool objects or a Toolset that the model can use. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :---------------------------------------------------- | | `replies` | List[ChatMessage] | A list containing the generated ChatMessage responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------- | :--------------------------------- | :-------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var(['GOOGLE_API_KEY', 'GEMINI_API_KEY'], strict=False) | Google API key, defaults to the `GOOGLE_API_KEY` and `GEMINI_API_KEY` environment variables. Not needed if using Vertex AI with Application Default Credentials. Go to [Google AI Studio](https://aistudio.google.com/app/apikey) for a Gemini API key. Go to [Google Cloud Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/start/api-keys) for a Vertex AI API key. | | `api` | Literal['gemini', 'vertex'] | gemini | The API to use. Either "gemini" for the Gemini Developer API or "vertex" for Vertex AI. | | `vertex_ai_project` | Optional[str] | None | Google Cloud project ID for Vertex AI. Required when using Vertex AI with Application Default Credentials. | | `vertex_ai_location` | Optional[str] | None | Google Cloud location for Vertex AI (for example, "us-central1", "europe-west1"). Required when using Vertex AI with Application Default Credentials. | | `model` | str | gemini-2.0-flash | Name of the model to use (for example, "gemini-2.0-flash"). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Configuration for generation (temperature, max_tokens, and more). | | `safety_settings` | Optional[List[Dict[str, Any]]] | None | Safety settings for content filtering. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of Tool objects or a Toolset that the model can use. Each tool should have a unique name. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Configuration for generation. | | `safety_settings` | Optional[List[Dict[str, Any]]] | None | Safety settings for content filtering. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of Tool objects or a Toolset that the model can use. | ## Related Information - [Use Google Gemini Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-googleai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## GoogleGenAIDocumentEmbedder Compute document embeddings using Google AI models. ## Key Features - Computes document embeddings using Google AI models - Supports both the Gemini Developer API and Vertex AI - Stores embeddings in each document's `embedding` field - Batch processing for efficient embedding of large document sets - Optional metadata field embedding alongside document text ## Configuration 1. Drag the `GoogleGenAIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Choose the API to use: `gemini` for the Gemini Developer API or `vertex` for Vertex AI. 2. For the Gemini Developer API, enter your Google API key (`GOOGLE_API_KEY` or `GEMINI_API_KEY`). For Vertex AI, enter your GCP project ID and location. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 3. Select an embedding model. For supported models, see the [Google AI documentation](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). 4. Go to the **Advanced** tab to configure batch size, metadata fields to embed, and other settings. ## Connections `GoogleGenAIDocumentEmbedder` accepts a list of `Document` objects through its `documents` input. It outputs a list of `Document` objects with the embeddings stored in the `embedding` field, and a `meta` dictionary with model usage information. Use this component in an indexing pipeline. Connect preprocessors like `DocumentSplitter` to its `documents` input, and connect its `documents` output to `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_genai/src/haystack_integrations/components/embedders/google_genai/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml GoogleGenAIDocumentEmbedder: type: haystack_integrations.components.embedders.google_genai.document_embedder.GoogleGenAIDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini model: text-embedding-004 prefix: '' suffix: '' batch_size: 32 progress_bar: true embedding_separator: "\n" ``` This index uses `GoogleGenAIDocumentEmbedder` to embed documents before storing them: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 GoogleGenAIDocumentEmbedder: type: haystack_integrations.components.embedders.google_genai.document_embedder.GoogleGenAIDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini vertex_ai_project: vertex_ai_location: model: text-embedding-004 prefix: "" suffix: "" batch_size: 32 progress_bar: true meta_fields_to_embed: embedding_separator: "\n" config: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'google-embeddings' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: GoogleGenAIDocumentEmbedder.documents - sender: GoogleGenAIDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :---------- | :------------ | :---------------------------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :------------ | :------------------------------------ | | `documents` | List[Document] | A list of documents with embeddings. | | `meta` | Dict[str, Any] | Information about the usage of the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------- | :-------------------------- | :-------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var(['GOOGLE_API_KEY', 'GEMINI_API_KEY'], strict=False) | Google API key. Not needed if using Vertex AI with Application Default Credentials. | | `api` | Literal['gemini', 'vertex'] | gemini | Which API to use. Either "gemini" for the Gemini Developer API or "vertex" for Vertex AI. | | `vertex_ai_project` | Optional[str] | None | Google Cloud project ID for Vertex AI. Required when using Vertex AI with Application Default Credentials. | | `vertex_ai_location` | Optional[str] | None | Google Cloud location for Vertex AI (for example, "us-central1", "europe-west1"). Required when using Vertex AI with Application Default Credentials. | | `model` | str | text-embedding-004 | The name of the model to use for calculating embeddings. | | `prefix` | str | "" | A string to add at the beginning of each text. | | `suffix` | str | "" | A string to add at the end of each text. | | `batch_size` | int | 32 | Number of documents to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when running. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | \n | Separator used to concatenate the metadata fields to the document text. | | `config` | Optional[Dict[str, Any]] | None | A dictionary to configure embedding content configuration. Defaults to `{"task_type": "SEMANTIC_SIMILARITY"}`. See [Google AI Task types](https://ai.google.dev/gemini-api/docs/embeddings#task-types). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :---------------------------- | | `documents` | List[Document] | A list of documents to embed. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google AI Task types](https://ai.google.dev/gemini-api/docs/embeddings#task-types) --- ## GoogleGenAITextEmbedder Embed strings using Google AI models. ## Key Features - Embeds text strings using Google AI models - Supports both the Gemini Developer API and Vertex AI - Use in query pipelines to embed user queries for semantic search - Returns a vector embedding alongside model usage metadata ## Configuration 1. Drag the `GoogleGenAITextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Choose the API to use: `gemini` for the Gemini Developer API or `vertex` for Vertex AI. 2. For the Gemini Developer API, enter your Google API key (`GOOGLE_API_KEY` or `GEMINI_API_KEY`). For Vertex AI, enter your GCP project ID and location. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 3. Select an embedding model. Use the same model as the one used to embed the documents in your document store. For supported models, see the [Google AI documentation](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). 4. Go to the **Advanced** tab to configure prefix, suffix, and task type settings. ## Connections `GoogleGenAITextEmbedder` accepts a text string through its `text` input. It outputs the embedding as a list of floats (`embedding`) and a `meta` dictionary with model usage information. Connect the `Input` component's `query` output to this component's `text` input. Connect the `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_genai/src/haystack_integrations/components/embedders/google_genai/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml GoogleGenAITextEmbedder: type: haystack_integrations.components.embedders.google_genai.text_embedder.GoogleGenAITextEmbedder init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini model: text-embedding-004 prefix: '' suffix: '' ``` This query pipeline uses `GoogleGenAITextEmbedder` to embed queries for semantic search: ```yaml # haystack-pipeline components: GoogleGenAITextEmbedder: type: haystack_integrations.components.embedders.google_genai.text_embedder.GoogleGenAITextEmbedder init_parameters: api_key: type: env_var env_vars: - GOOGLE_API_KEY - GEMINI_API_KEY strict: false api: gemini vertex_ai_project: vertex_ai_location: model: text-embedding-004 prefix: "" suffix: "" config: embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'google-embeddings' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: "You are a helpful assistant answering questions based on the provided documents." - role: user content: "Documents:\n{% for doc in documents %}\n{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: GoogleGenAITextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies - sender: embedding_retriever.documents receiver: answer_builder.documents inputs: query: - GoogleGenAITextEmbedder.text - ChatPromptBuilder.query - answer_builder.query filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :--------------- | | `text` | str | Text to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :------------ | :---------------------------------- | | `embedding` | List[float] | The embedding of the input text. | | `meta` | Dict[str, Any] | Information about the usage of the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :-------------------------- | :-------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var(['GOOGLE_API_KEY', 'GEMINI_API_KEY'], strict=False) | Google API key. Not needed if using Vertex AI with Application Default Credentials. | | `api` | Literal['gemini', 'vertex'] | gemini | Which API to use. Either "gemini" for the Gemini Developer API or "vertex" for Vertex AI. | | `vertex_ai_project` | Optional[str] | None | Google Cloud project ID for Vertex AI. Required when using Vertex AI with Application Default Credentials. | | `vertex_ai_location` | Optional[str] | None | Google Cloud location for Vertex AI (for example, "us-central1", "europe-west1"). Required when using Vertex AI with Application Default Credentials. | | `model` | str | text-embedding-004 | The name of the model to use for calculating embeddings. | | `prefix` | str | "" | A string to add at the beginning of each text to embed. | | `suffix` | str | "" | A string to add at the end of each text to embed. | | `config` | Optional[Dict[str, Any]] | None | A dictionary to configure embedding content configuration. Defaults to `{"task_type": "SEMANTIC_SIMILARITY"}`. See [Google AI Task types](https://ai.google.dev/gemini-api/docs/embeddings#task-types). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :------------- | | `text` | str | Text to embed. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google AI Task types](https://ai.google.dev/gemini-api/docs/embeddings#task-types) --- ## AnthropicVertexChatGenerator Generate text using Claude models through the Anthropic Vertex AI API. ## Key Features - Chat completion using Claude models (including Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Sonnet, and Claude 3 Haiku) through Vertex AI - Streaming support for real-time token-by-token responses - Tool/function calling support - Configurable generation parameters (temperature, top_p, max_tokens, and more) - Requires a GCP project with Vertex AI enabled and the desired Claude model activated in the Vertex AI Model Garden ## Configuration 1. Drag the `AnthropicVertexChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP region (defaults to "us-central1") and project ID. Create secrets called `REGION` and `PROJECT_ID` for these values. For details, see [Add a secret](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select a model. Make sure the model is activated in the Vertex AI Model Garden. For details, see [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx). 4. Go to the **Advanced** tab to configure generation parameters, timeout, max retries, tools, and streaming. ## Connections `AnthropicVertexChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`vertex_chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/vertex_chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AnthropicVertexChatGenerator: type: haystack_integrations.components.generators.anthropic.chat.vertex_chat_generator.AnthropicVertexChatGenerator init_parameters: model: claude-3-5-sonnet@20240620 ignore_tools_thinking_messages: true ``` ### Using the Component in a Pipeline This is an example of a RAG pipeline with AnthropicVertexChatGenerator: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false AnthropicVertexChatGenerator: type: haystack_integrations.components.generators.anthropic.chat.vertex_chat_generator.AnthropicVertexChatGenerator init_parameters: region: project_id: model: claude-3-5-sonnet@20240620 streaming_callback: generation_kwargs: ignore_tools_thinking_messages: true tools: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: AnthropicVertexChatGenerator.replies receiver: OutputAdapter.replies - sender: ChatPromptBuilder.prompt receiver: AnthropicVertexChatGenerator.messages inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Anthropic generation endpoint. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of Tool objects or a Toolset that the model can use. If set, it overrides the `tools` parameter set during initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :--------------------------- | | `replies` | List[ChatMessage] | The responses from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------------------- | :--------------------------------------- | :---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `region` | str | | The region where the Anthropic model is deployed. Defaults to "us-central1". | | `project_id` | str | | The GCP project ID where the Anthropic model is deployed. | | `model` | str | claude-sonnet-4@20250514 | The name of the model to use. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model. These parameters are all sent directly to the AnthropicVertex endpoint. See Anthropic [documentation](https://docs.anthropic.com/claude/reference/messages_post) for more details. Supported generation_kwargs parameters are: `system` (the system message), `max_tokens` (the maximum number of tokens to generate), `metadata` (a dictionary of metadata), `stop_sequences` (a list of strings that the model should stop generating at), `temperature` (the temperature to use for sampling), `top_p`, `top_k`, `extra_headers` (a dictionary of extra headers for beta features). | | `ignore_tools_thinking_messages` | bool | True | If `True`, drops "chain of thought" thinking messages when tool use is detected. See the Anthropic [tools](https://docs.anthropic.com/en/docs/tool-use#chain-of-thought-tool-use) for more details. | | `tools` | Optional[List[Tool]] | None | A list of Tool objects that the model can use. Each tool should have a unique name. | | `timeout` | Optional[float] | None | Timeout for Anthropic client calls. If not set, defaults to the Anthropic client's default. | | `max_retries` | Optional[int] | None | Maximum number of retries to attempt for failed requests. If not set, defaults to the Anthropic client's default. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | ## Related Information - [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx) - [Add a secret](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## VertexAICodeGenerator Generate code using Google Vertex AI generative models. ## Key Features - Code generation and completion using Google Vertex AI models (code-bison, code-bison-32k, code-gecko) - Code completion task: provide a code prefix (and optionally a suffix) and the model fills in the code in between - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAICodeGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select a model. Supported models: `code-bison`, `code-bison-32k`, `code-gecko`. 3. Optionally, enter the location. If not set, uses `us-central1`. 4. Go to the **Advanced** tab to configure additional model keyword arguments. ## Connections `VertexAICodeGenerator` accepts a `prefix` (str) input and an optional `suffix` (Optional[str]) input. It outputs generated code snippets as `replies` (a list of strings). Connect the `prefix` input to the query output from the `Input` component or from `PromptBuilder`. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`code_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/code_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAICodeGenerator: type: haystack_integrations.components.generators.google_vertex.code_generator.VertexAICodeGenerator init_parameters: model: code-bison ``` This pipeline uses `VertexAICodeGenerator` to generate code: ```yaml # haystack-pipeline components: VertexAICodeGenerator: type: haystack_integrations.components.generators.google_vertex.code_generator.VertexAICodeGenerator init_parameters: model: code-bison project_id: location: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true connections: - sender: VertexAICodeGenerator.replies receiver: AnswerBuilder.replies max_runs_per_component: 100 metadata: {} inputs: query: - VertexAICodeGenerator.prefix - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :------------- | :------ | :-------------------------------- | | `prefix` | str | | Code before the current point. | | `suffix` | Optional[str] | None | Code after the current point. | ### Outputs | Parameter | Type | Description | | :-------- | :-------- | :-------------------------------------- | | `replies` | List[str] | A list of generated code snippets. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :------------ | :-------- | :------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | code-bison | Name of the model to use. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `kwargs` | Any | | Additional keyword arguments to pass to the model. See the `TextGenerationModel.predict()` documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :------------ | :------ | :----------------------------- | | `prefix` | str | | Code before the current point. | | `suffix` | Optional[str] | None | Code after the current point. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAIDocumentEmbedder Embed documents using Vertex AI Embeddings API. ## Key Features - Embeds documents using the Vertex AI Embeddings API - Configurable task type (RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, and others) - Batch processing support for efficient embedding of large document sets - Built-in retry logic for reliability - Stores embeddings in each document's `embedding` field ## Configuration 1. Drag the `VertexAIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID and region. Create secrets with the keys `GCP_PROJECT_ID` and `GCP_DEFAULT_REGION`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select a model. For supported models, see the official [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#syntax). 3. Select a task type. Use `RETRIEVAL_DOCUMENT` when embedding documents for storage. 4. Go to the **Advanced** tab to configure batch size, retries, truncation, and metadata field settings. ## Connections `VertexAIDocumentEmbedder` accepts a list of `Document` objects through its `documents` input. It outputs a list of `Document` objects with embeddings stored in the `embedding` field. Use this component in an indexing pipeline. Connect preprocessors like `DocumentSplitter` to its `documents` input, and connect its `documents` output to `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/embedders/google_vertex/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIDocumentEmbedder: type: haystack_integrations.components.embedders.google_vertex.document_embedder.VertexAIDocumentEmbedder init_parameters: model: text-embedding-005 task_type: RETRIEVAL_DOCUMENT gcp_region_name: type: env_var env_vars: - GCP_DEFAULT_REGION strict: false gcp_project_id: type: env_var env_vars: - GCP_PROJECT_ID strict: false batch_size: 32 max_tokens_total: 20000 time_sleep: 30 retries: 3 progress_bar: true embedding_separator: "\n" ``` This index uses `VertexAIDocumentEmbedder` to embed documents before storing them: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 VertexAIDocumentEmbedder: type: haystack_integrations.components.embedders.google_vertex.document_embedder.VertexAIDocumentEmbedder init_parameters: model: text-embedding-005 task_type: RETRIEVAL_DOCUMENT gcp_region_name: type: env_var env_vars: - GCP_DEFAULT_REGION strict: false gcp_project_id: type: env_var env_vars: - GCP_PROJECT_ID strict: false batch_size: 32 max_tokens_total: 20000 time_sleep: 30 retries: 3 progress_bar: true truncate_dim: meta_fields_to_embed: embedding_separator: "\n" DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'vertex-embeddings' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: VertexAIDocumentEmbedder.documents - sender: VertexAIDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :------------ | :---------------------------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :----------------------------------- | | `documents` | List[Document] | A list of documents with embeddings. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------- | :----------------------------------------------------------- | :---------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | Literal['text-embedding-004', 'text-embedding-005', ...] | | Name of the model to use. | | `task_type` | Literal['RETRIEVAL_DOCUMENT', 'RETRIEVAL_QUERY', ...] | RETRIEVAL_DOCUMENT | The type of task for which the embeddings are being generated. See [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#tasktype). | | `gcp_region_name` | Optional[Secret] | Secret.from_env_var('GCP_DEFAULT_REGION', strict=False) | The default location to use when making API calls. If not set, uses us-central-1. | | `gcp_project_id` | Optional[Secret] | Secret.from_env_var('GCP_PROJECT_ID', strict=False) | ID of the GCP project to use. | | `batch_size` | int | 32 | The number of documents to process in a single batch. | | `max_tokens_total` | int | 20000 | The maximum number of tokens to process in total. | | `time_sleep` | int | 30 | The time to sleep between retries in seconds. | | `retries` | int | 3 | The number of retries in case of failure. | | `progress_bar` | bool | True | Whether to display a progress bar during processing. | | `truncate_dim` | Optional[int] | None | The dimension to truncate the embeddings to, if specified. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of metadata fields to include in the embeddings. | | `embedding_separator` | str | \n | The separator to use between different embeddings. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :---------------------------- | | `documents` | List[Document] | A list of documents to embed. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAIGeminiChatGenerator Complete chats using Google Gemini models through Vertex AI. ## Key Features - Chat completion using Google Gemini models on Vertex AI - Streaming support for real-time token-by-token responses - Tool/function calling support - Configurable safety settings for content filtering - Configurable generation parameters (temperature, top_p, and more) - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAIGeminiChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. You must have an account with a project authorized to use Google Vertex AI endpoints. Find your project ID in the GCP resource manager. 2. Optionally, enter the location. If not set, uses `us-central1`. 3. Select a model. For available models, see [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models). 4. Go to the **Advanced** tab to configure generation settings, safety settings, tools, tool configuration, and streaming. ## Connections `VertexAIGeminiChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`gemini.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/chat/gemini.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIGeminiChatGenerator: type: haystack_integrations.components.generators.google_vertex.chat.gemini.VertexAIGeminiChatGenerator init_parameters: model: gemini-1.5-flash ``` ### Using the Component in a Pipeline This is an example RAG pipeline with `VertexAIGeminiChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false VertexAIGeminiChatGenerator: type: haystack_integrations.components.generators.google_vertex.chat.gemini.VertexAIGeminiChatGenerator init_parameters: model: gemini-1.5-flash project_id: location: generation_config: safety_settings: tools: tool_config: streaming_callback: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: VertexAIGeminiChatGenerator.messages - sender: VertexAIGeminiChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. If set, overrides the `tools` parameter set during initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :------------------------------------------------------------------- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------------- | :--------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | str | gemini-1.5-flash | Name of the model to use. For available models, see [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models). | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `generation_config` | Optional[Union[GenerationConfig, Dict[str, Any]]] | None | Configuration for the generation process. See the [GenerationConfig documentation](https://cloud.google.com/python/docs/reference/aiplatform/latest/vertexai.generative_models.GenerationConfig) for a list of supported arguments. | | `safety_settings` | Optional[Dict[HarmCategory, HarmBlockThreshold]] | None | Safety settings to use when generating content. See the documentation for [HarmBlockThreshold](https://cloud.google.com/python/docs/reference/aiplatform/latest/vertexai.generative_models.HarmBlockThreshold) and [HarmCategory](https://cloud.google.com/python/docs/reference/aiplatform/latest/vertexai.generative_models.HarmCategory) for more details. | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. | | `tool_config` | Optional[ToolConfig] | None | The tool config to use. See the documentation for [ToolConfig](https://cloud.google.com/vertex-ai/generative-ai/docs/reference/python/latest/vertexai.generative_models.ToolConfig). | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[List[Tool]] | None | A list of tools for which the model can prepare calls. If set, overrides the `tools` parameter set during initialization. | ## Related Information - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## VertexAIGeminiGenerator Generate text using Google Gemini models through Vertex AI. :::warning Deprecation Notice This integration will be deprecated soon. We recommend using `GoogleGenAIChatGenerator` instead, which provides unified access to both Gemini Developer API and Vertex AI. ::: ## Key Features - Text generation using Google Gemini models through Vertex AI - Supports multimodal inputs including text and images - Streaming support for real-time token-by-token responses - Designed for text generation, not chat (use `GoogleGenAIChatGenerator` for chat capabilities) - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAIGeminiGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally, enter the location. If not set, uses `us-central1`. 3. Select a model. For available models, see [Vertex AI models](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models). 4. Go to the **Advanced** tab to configure generation settings, safety settings, system instruction, and streaming. ## Connections `VertexAIGeminiGenerator` accepts multimodal inputs through its `parts` input — a list of strings, `ByteStream` objects, or `Part` objects. It outputs generated text as `replies` (a list of strings). Connect `PromptBuilder`'s `prompt` output to this component's `parts` input. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`gemini.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/gemini.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIGeminiGenerator: type: haystack_integrations.components.generators.google_vertex.gemini.VertexAIGeminiGenerator init_parameters: model: gemini-2.0-flash ``` This query pipeline uses `VertexAIGeminiGenerator` to generate text responses: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 fuzziness: 0 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }} required_variables: variables: VertexAIGeminiGenerator: type: haystack_integrations.components.generators.google_vertex.gemini.VertexAIGeminiGenerator init_parameters: project_id: model: gemini-2.0-flash location: generation_config: safety_settings: system_instruction: streaming_callback: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: bm25_retriever.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: VertexAIGeminiGenerator.parts - sender: VertexAIGeminiGenerator.replies receiver: AnswerBuilder.replies - sender: bm25_retriever.documents receiver: AnswerBuilder.documents inputs: query: - bm25_retriever.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------- | :------ | :----------------------------------------------------------------------- | | `parts` | Variadic[Union[str, ByteStream, Part]] | | Prompt for the model. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ### Outputs | Parameter | Type | Description | | :-------- | :-------- | :------------------------------ | | `replies` | List[str] | A list of generated content. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------ | :----------------------------------------------- | :--------------- | :---------------------------------------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | gemini-2.0-flash | Name of the model to use. For available models, see [Vertex AI models](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models). | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `generation_config` | Optional[Union[GenerationConfig, Dict[str, Any]]] | None | The generation config to use. Accepted fields: temperature, top_p, top_k, candidate_count, max_output_tokens, stop_sequences. | | `safety_settings` | Optional[Dict[HarmCategory, HarmBlockThreshold]] | None | The safety settings to use. | | `system_instruction` | Optional[Union[str, ByteStream, Part]] | None | Default system instruction to use for generating content. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :----------------------------------------- | :------ | :----------------------------------------------------------------------- | | `parts` | Variadic[Union[str, ByteStream, Part]] | | Prompt for the model. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [GoogleGenAIChatGenerator](/docs/reference/pipeline-components/integrations/google-ai/GoogleGenAIChatGenerator.mdx) --- ## VertexAIImageCaptioner Generate captions for images using Google Vertex AI imagetext model. ## Key Features - Generates descriptive captions for images using the Vertex AI imagetext model - Accepts images as `ByteStream` input - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAIImageCaptioner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally, enter the location. If not set, uses `us-central1`. 3. The default model is `imagetext`. 4. Go to the **Advanced** tab to configure additional model keyword arguments. ## Connections `VertexAIImageCaptioner` accepts an image as a `ByteStream` object through its `image` input. It outputs generated captions as `captions` (a list of strings). Connect an image source to the `image` input. Connect the `captions` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`captioner.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/captioner.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIImageCaptioner: type: haystack_integrations.components.generators.google_vertex.captioner.VertexAIImageCaptioner init_parameters: model: imagetext ``` This pipeline uses `VertexAIImageCaptioner` to generate captions for images: ```yaml # haystack-pipeline components: VertexAIImageCaptioner: type: haystack_integrations.components.generators.google_vertex.captioner.VertexAIImageCaptioner init_parameters: project_id: model: imagetext location: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: VertexAIImageCaptioner.captions receiver: AnswerBuilder.replies inputs: image: - VertexAIImageCaptioner.image query: - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--------- | :------------------------------------ | | `image` | ByteStream | The image to generate captions for. | ### Outputs | Parameter | Type | Description | | :-------- | :-------- | :----------------------------------------- | | `captions` | List[str] | A list of captions generated by the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :------------ | :-------- | :------------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | imagetext | Name of the model to use. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `kwargs` | Any | | Additional keyword arguments to pass to the model. See the `ImageTextModel.get_captions()` documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--------- | :---------------------------------- | | `image` | ByteStream | The image to generate captions for. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAIImageGenerator Generate images using Google Vertex AI generative model. ## Key Features - Generates images from text prompts using Google Vertex AI - Supports negative prompts to exclude unwanted elements from generated images - Returns images as `ByteStream` objects - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAIImageGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally, enter the location. If not set, uses `us-central1`. 3. The default model is `imagegeneration`. 4. Go to the **Advanced** tab to configure additional model keyword arguments. ## Connections `VertexAIImageGenerator` accepts a text `prompt` (str) and an optional `negative_prompt` (Optional[str]) as inputs. It outputs generated images as a list of `ByteStream` objects through its `images` output. Connect `PromptBuilder`'s `prompt` output to this component's `prompt` input. ## Source Code To check this component's source code, open [`image_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/image_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIImageGenerator: type: haystack_integrations.components.generators.google_vertex.image_generator.VertexAIImageGenerator init_parameters: model: imagegeneration ``` This pipeline uses `VertexAIImageGenerator` to generate images from text prompts: ```yaml # haystack-pipeline components: VertexAIImageGenerator: type: haystack_integrations.components.generators.google_vertex.image_generator.VertexAIImageGenerator init_parameters: project_id: model: imagegeneration location: PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Generate an image described in the query.\n\nQuery: {{ query }}" required_variables: "\\n" variables: max_runs_per_component: 100 metadata: {} connections: - sender: PromptBuilder.prompt receiver: VertexAIImageGenerator.prompt inputs: query: - PromptBuilder.query ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------------- | :------------ | :------ | :--------------------------------------------------------------- | | `prompt` | str | | The prompt to generate images from. | | `negative_prompt` | Optional[str] | None | A description of what you want to omit in the generated images. | ### Outputs | Parameter | Type | Description | | :-------- | :---------------- | :------------------------------------------------------- | | `images` | List[ByteStream] | A list of ByteStream objects, each containing an image. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :------------ | :--------------- | :---------------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | imagegeneration | Name of the model to use. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `kwargs` | Any | | Additional keyword arguments to pass to the model. See the `ImageGenerationModel.generate_images()` documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------------- | :------------ | :------ | :-------------------------------------------------------------- | | `prompt` | str | | The prompt to generate images from. | | `negative_prompt` | Optional[str] | None | A description of what you want to omit in the generated images. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAIImageQA Answer questions about images using Google Vertex AI generative models. ## Key Features - Answers questions about images using Google Vertex AI visual question answering models - Accepts an image as `ByteStream` and a question as string inputs - Returns answers based on the image content - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAIImageQA` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally, enter the location. If not set, uses `us-central1`. 3. The default model is `imagetext`. 4. Go to the **Advanced** tab to configure additional model keyword arguments. ## Connections `VertexAIImageQA` accepts an `image` (ByteStream) and a `question` (str) as inputs. It outputs answers as `replies` (a list of strings). Connect an image source to the `image` input and a question string to the `question` input. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`question_answering.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/question_answering.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAIImageQA: type: haystack_integrations.components.generators.google_vertex.question_answering.VertexAIImageQA init_parameters: model: imagetext ``` This pipeline uses `VertexAIImageQA` to answer questions about images: ```yaml # haystack-pipeline components: VertexAIImageQA: type: haystack_integrations.components.generators.google_vertex.question_answering.VertexAIImageQA init_parameters: project_id: model: imagetext location: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: VertexAIImageQA.replies receiver: AnswerBuilder.replies outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} inputs: query: - VertexAIImageQA.question - AnswerBuilder.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--------- | :--------- | :---------------------------------- | | `image` | ByteStream | The image to ask the question about. | | `question` | str | The question to ask. | ### Outputs | Parameter | Type | Description | | :-------- | :-------- | :---------------------------------- | | `replies` | List[str] | A list of answers to the question. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :------------ | :-------- | :---------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | imagetext | Name of the model to use. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `kwargs` | Any | | Additional keyword arguments to pass to the model. See the `ImageTextModel.ask_question()` documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--------- | :----------------------------------- | | `image` | ByteStream | The image to ask the question about. | | `question` | str | The question to ask. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAITextEmbedder Embed text using Vertex AI Text Embeddings API. ## Key Features - Embeds text strings using the Vertex AI Text Embeddings API - Configurable task type for retrieval and other use cases - Use in query pipelines to embed user queries for semantic search - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAITextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID and region. Create secrets with the keys `GCP_PROJECT_ID` and `GCP_DEFAULT_REGION`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select a model. Use the same model as the one used to embed the documents in your document store. For supported models, see the official [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#syntax). 3. Select a task type. Use `RETRIEVAL_QUERY` when embedding queries for retrieval. 4. Go to the **Advanced** tab to configure the progress bar and embedding dimension truncation. ## Connections `VertexAITextEmbedder` accepts a text input and outputs the embedding as a list of floats (`embedding`). Connect the `Input` component's `query` output to this component's `text` input. Connect the `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/embedders/google_vertex/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAITextEmbedder: type: haystack_integrations.components.embedders.google_vertex.text_embedder.VertexAITextEmbedder init_parameters: model: text-embedding-005 task_type: RETRIEVAL_QUERY gcp_region_name: type: env_var env_vars: - GCP_DEFAULT_REGION strict: false gcp_project_id: type: env_var env_vars: - GCP_PROJECT_ID strict: false progress_bar: true ``` This query pipeline uses `VertexAITextEmbedder` to embed queries for semantic search: ```yaml # haystack-pipeline components: VertexAITextEmbedder: type: haystack_integrations.components.embedders.google_vertex.text_embedder.VertexAITextEmbedder init_parameters: model: text-embedding-005 task_type: RETRIEVAL_QUERY gcp_region_name: type: env_var env_vars: - GCP_DEFAULT_REGION strict: false gcp_project_id: type: env_var env_vars: - GCP_PROJECT_ID strict: false progress_bar: true truncate_dim: embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'vertex-embeddings' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: "You are a helpful assistant answering questions based on the provided documents." - role: user content: "Documents:\n{% for doc in documents %}\n{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: VertexAITextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies - sender: embedding_retriever.documents receiver: answer_builder.documents inputs: query: - VertexAITextEmbedder.text - ChatPromptBuilder.query - answer_builder.query filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :---------------------------------- | :--------------- | | `text` | Union[List[Document], List[str], str] | The text to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :---------- | :------------------------------- | | `embedding` | List[float] | The embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------- | :------------------------------------------------------- | :---------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | Literal['text-embedding-004', 'text-embedding-005', ...] | | Name of the model to use. | | `task_type` | Literal['RETRIEVAL_DOCUMENT', 'RETRIEVAL_QUERY', ...] | RETRIEVAL_QUERY | The type of task for which the embeddings are being generated. See [Google documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#tasktype). | | `gcp_region_name` | Optional[Secret] | Secret.from_env_var('GCP_DEFAULT_REGION', strict=False) | The default location to use when making API calls. If not set, uses us-central-1. | | `gcp_project_id` | Optional[Secret] | Secret.from_env_var('GCP_PROJECT_ID', strict=False) | ID of the GCP project to use. | | `progress_bar` | bool | True | Whether to display a progress bar during processing. | | `truncate_dim` | Optional[int] | None | The dimension to truncate the embeddings to, if specified. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :---------------------------------- | :----------------- | | `text` | Union[List[Document], List[str], str] | The text to embed. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## VertexAITextGenerator Generate text using Google Vertex AI generative models. ## Key Features - Text generation using Google Vertex AI models (text-bison, text-unicorn, text-bison-32k) - Returns generated replies along with safety attributes and citations - Authenticates using Google Cloud Application Default Credentials (ADCs) ## Configuration 1. Drag the `VertexAITextGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter your GCP project ID. Create a secret with the key `GCP_PROJECT_ID`. For detailed instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Optionally, enter the location. If not set, uses `us-central1`. 3. Select a model. Supported models: `text-bison`, `text-unicorn`, `text-bison-32k`. 4. Go to the **Advanced** tab to configure additional model keyword arguments. ## Connections `VertexAITextGenerator` accepts a text `prompt` (str) through its `prompt` input. It outputs `replies` (a list of strings), `safety_attributes` (a dictionary of safety scores), and `citations` (a list of citation dictionaries). Connect `PromptBuilder`'s `prompt` output to this component's `prompt` input. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`text_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_vertex/src/haystack_integrations/components/generators/google_vertex/text_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VertexAITextGenerator: type: haystack_integrations.components.generators.google_vertex.text_generator.VertexAITextGenerator init_parameters: model: text-bison ``` This query pipeline uses `VertexAITextGenerator` to generate text responses: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 fuzziness: 0 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }} required_variables: variables: VertexAITextGenerator: type: haystack_integrations.components.generators.google_vertex.text_generator.VertexAITextGenerator init_parameters: project_id: model: text-bison location: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: bm25_retriever.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: VertexAITextGenerator.prompt - sender: VertexAITextGenerator.replies receiver: AnswerBuilder.replies - sender: bm25_retriever.documents receiver: AnswerBuilder.documents inputs: query: - bm25_retriever.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :----------------------------------- | | `prompt` | str | The prompt to use for text generation. | ### Outputs | Parameter | Type | Description | | :----------------- | :---------------------- | :---------------------------------- | | `replies` | List[str] | A list of generated replies. | | `safety_attributes` | Dict[str, float] | Safety scores for each answer. | | `citations` | List[Dict[str, Any]] | Citations for each answer. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :------------ | :--------- | :------------------------------------------------------------------------------------------------------- | | `project_id` | Optional[str] | None | ID of the GCP project to use. By default, it is set during Google Cloud authentication. | | `model` | str | text-bison | Name of the model to use. | | `location` | Optional[str] | None | The default location to use when making API calls. If not set, uses us-central-1. | | `kwargs` | Any | | Additional keyword arguments to pass to the model. See the `TextGenerationModel.predict()` documentation. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :------------------------------------- | | `prompt` | str | The prompt to use for text generation. | ## Related Information - [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) - [Google Cloud Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) --- ## HuggingFaceAPIChatGenerator Complete chats using Hugging Face APIs. ## Key Features - Chat completion using Hugging Face APIs: Serverless Inference API (Inference Providers), paid Inference Endpoints, and self-hosted Text Generation Inference (TGI) - Multimodal support: send both text and images to Vision Language Models (VLMs) - Streaming support for real-time token-by-token responses - Tool/function calling support - Consistent `finish_reason` behavior regardless of streaming mode ## Configuration 1. Drag the `HuggingFaceAPIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the API type: `serverless_inference_api`, `inference_endpoints`, or `text_generation_inference`. 2. Enter the API parameters: for `serverless_inference_api`, enter the model ID; for `inference_endpoints` or `text_generation_inference`, enter the endpoint URL. 3. Enter your Hugging Face API token. Connect to your Hugging Face account first. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 4. Go to the **Advanced** tab to configure generation parameters, stop words, tools, and streaming. ## Connections `HuggingFaceAPIChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`hugging_face_api.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/hugging_face_api.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceAPIChatGenerator: type: haystack.components.generators.chat.hugging_face_api.HuggingFaceAPIChatGenerator init_parameters: api_type: serverless_inference_api api_params: model: HuggingFaceH4/zephyr-7b-beta token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false ``` ### Using the Component in a Pipeline This is an example RAG pipeline with `HuggingFaceAPIChatGenerator` and `DeepsetAnswerBuilder`. `HuggingFaceAPIChatGenerator` is configured to use the serverless inference API: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false HuggingFaceAPIChatGenerator: type: haystack.components.generators.chat.hugging_face_api.HuggingFaceAPIChatGenerator init_parameters: api_type: serverless_inference_api api_params: model: HuggingFaceH4/zephyr-7b-beta token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: stop_words: streaming_callback: tools: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: HuggingFaceAPIChatGenerator.messages - sender: HuggingFaceAPIChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :------------------------------------------------------------------ | | `replies` | List[ChatMessage] | A list containing the generated responses as ChatMessage objects. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `api_type` | Union[HFGenerationAPIType, str] | | The type of Hugging Face API to use. Available types: `text_generation_inference` (see [TGI](https://github.com/huggingface/text-generation-inference)), `inference_endpoints` (see [Inference Endpoints](https://huggingface.co/inference-endpoints)), `serverless_inference_api` (see [Serverless Inference API](https://huggingface.co/docs/inference-providers)). | | `api_params` | Dict[str, str] | | A dictionary with: `model` (Hugging Face model ID, required for `SERVERLESS_INFERENCE_API`), `provider` (recommended for `SERVERLESS_INFERENCE_API`), `url` (required for `INFERENCE_ENDPOINTS` or `TEXT_GENERATION_INFERENCE`), and other parameters specific to the chosen API type. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token to use as HTTP bearer authorization. Check your HF token in your [account settings](https://huggingface.co/settings/tokens). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary with keyword arguments to customize text generation. Some examples: `max_tokens`, `temperature`, `top_p`. For details, see [Hugging Face chat_completion documentation](https://huggingface.co/docs/huggingface_hub/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion). | | `stop_words` | Optional[List[str]] | None | An optional list of strings representing the stop words. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :----------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## HuggingFaceAPIDocumentEmbedder Embed documents using Hugging Face APIs. ## Key Features - Embeds documents using Hugging Face APIs: free Serverless Inference API, paid Inference Endpoints, and self-hosted Text Embeddings Inference (TEI) - Batch processing for efficient embedding of large document sets - Optional metadata field embedding alongside document text - Stores embeddings in each document's `embedding` field ## Configuration 1. Drag the `HuggingFaceAPIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the API type: `SERVERLESS_INFERENCE_API`, `INFERENCE_ENDPOINTS`, or `TEXT_EMBEDDINGS_INFERENCE`. 2. Enter the API parameters: for `SERVERLESS_INFERENCE_API`, enter the model ID; for `INFERENCE_ENDPOINTS` or `TEXT_EMBEDDINGS_INFERENCE`, enter the endpoint URL. 3. Enter your Hugging Face API token. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 4. Go to the **Advanced** tab to configure prefix, suffix, truncation, normalization, batch size, and metadata fields. ## Connections `HuggingFaceAPIDocumentEmbedder` accepts a list of `Document` objects through its `documents` input. It outputs a list of `Document` objects with embeddings stored in the `embedding` field. Use this component in an indexing pipeline. Connect preprocessors like `DocumentSplitter` to its `documents` input, and connect its `documents` output to `DocumentWriter`. ## Source Code To check this component's source code, open [`hugging_face_api_document_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/hugging_face_api_document_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceAPIDocumentEmbedder: type: haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder init_parameters: api_type: serverless_inference_api api_params: model: BAAI/bge-small-en-v1.5 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false prefix: '' suffix: '' truncate: true normalize: false batch_size: 32 progress_bar: true embedding_separator: \n ``` ### Using the Component in an Index This is an example index for preprocessing multiple document types. The documents resulting from file conversion are sent to `HuggingFaceAPIDocumentEmbedder`, which embeds them and sends them to `DocumentWriter` that writes them into an OpenSearch document store. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE HuggingFaceAPIDocumentEmbedder: type: haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder init_parameters: api_type: serverless_inference_api api_params: model: BAAI/bge-small-en-v1.5 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false prefix: '' suffix: '' truncate: true normalize: false batch_size: 32 progress_bar: true meta_fields_to_embed: embedding_separator: \n connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents - sender: splitter.documents receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: HuggingFaceAPIDocumentEmbedder.documents - sender: HuggingFaceAPIDocumentEmbedder.documents receiver: writer.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :------------ | :------------------ | | `documents` | List[Document] | Documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :----------------------------------- | | `documents` | List[Document] | A list of documents with embeddings. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------- | :---------------------------- | :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `api_type` | Union[HFEmbeddingAPIType, str] | | The type of Hugging Face API to use. Possible values: `SERVERLESS_INFERENCE_API` (free tier, requires model and api parameters), `INFERENCE_ENDPOINTS` (paid tier, requires URL and api parameters), `TEXT_EMBEDDINGS_INFERENCE` (self-hosted, requires URL and api parameters). | | `api_params` | Dict[str, str] | | A dictionary with: `model` (Hugging Face model ID, required for `SERVERLESS_INFERENCE_API`), `url` (URL of the inference endpoint, required for `INFERENCE_ENDPOINTS` or `TEXT_EMBEDDINGS_INFERENCE`). | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token used to connect to your Hugging Face account. Check your HF token in your [account settings](https://huggingface.co/settings/tokens). | | `prefix` | str | | A string to add at the beginning of each text. | | `suffix` | str | | A string to add at the end of each text. | | `truncate` | Optional[bool] | True | Truncates the input text to the maximum length supported by the model. Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE` or `INFERENCE_ENDPOINTS` if the backend uses Text Embeddings Inference. If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. | | `normalize` | Optional[bool] | False | Normalizes the embeddings to unit length. Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE` or `INFERENCE_ENDPOINTS` if the backend uses Text Embeddings Inference. If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored. | | `batch_size` | int | 32 | Number of documents to process at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when running. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | \n | Separator used to concatenate the metadata fields to the document text. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :------------ | :------------------ | | `documents` | List[Document] | Documents to embed. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) --- ## HuggingFaceAPIGenerator Generate text using Hugging Face APIs. :::warning Model Limitations As of July 2025, the Hugging Face Inference API no longer offers generative models through the `text_generation` endpoint. Generative models are now only available through providers supporting the `chat_completion` endpoint. This component might no longer work with the Hugging Face Inference API. Use the `HuggingFaceAPIChatGenerator` component instead, which supports the `chat_completion` endpoint and works with the free Serverless Inference API. ::: ## Key Features - Text generation using Hugging Face paid Inference Endpoints and self-hosted Text Generation Inference (TGI) - Streaming support for real-time token-by-token responses - Designed for text generation, not chat (use `HuggingFaceAPIChatGenerator` for chat) - Returns generated text along with metadata such as token count and finish reason ## Configuration 1. Drag the `HuggingFaceAPIGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the API type: `inference_endpoints` or `text_generation_inference`. 2. Enter the endpoint URL in the API parameters. 3. Enter your Hugging Face API token. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 4. Go to the **Advanced** tab to configure generation parameters, stop words, and streaming. ## Connections `HuggingFaceAPIGenerator` accepts a text `prompt` (str) through its `prompt` input. It outputs `replies` (a list of strings) and `meta` (a list of metadata dictionaries). Connect `PromptBuilder`'s `prompt` output to this component's `prompt` input. Connect the `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`hugging_face_api.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/hugging_face_api.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceAPIGenerator: type: haystack.components.generators.hugging_face_api.HuggingFaceAPIGenerator init_parameters: api_type: inference_endpoints api_params: url: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: max_new_tokens: 500 temperature: 0.7 ``` This query pipeline uses `HuggingFaceAPIGenerator` with a paid Inference Endpoint: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 fuzziness: 0 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }} required_variables: variables: HuggingFaceAPIGenerator: type: haystack.components.generators.hugging_face_api.HuggingFaceAPIGenerator init_parameters: api_type: inference_endpoints api_params: url: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: max_new_tokens: 500 temperature: 0.7 stop_words: streaming_callback: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: bm25_retriever.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: HuggingFaceAPIGenerator.prompt - sender: HuggingFaceAPIGenerator.replies receiver: AnswerBuilder.replies - sender: bm25_retriever.documents receiver: AnswerBuilder.documents inputs: query: - bm25_retriever.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------- | | `prompt` | str | | A string representing the prompt. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------------- | :---------------------------------------------------------------------------------------- | | `replies` | List[str] | A list of strings representing the generated replies. | | `meta` | List[Dict[str, Any]] | A list of dictionaries with metadata associated with each reply, such as token count and finish reason. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------- | :---------------------------- | :------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_type` | Union[HFGenerationAPIType, str] | | The type of Hugging Face API to use. Options: `text_generation_inference` (self-hosted TGI), `inference_endpoints` (paid endpoints), `serverless_inference_api` (free API, may not work for generative models). | | `api_params` | Dict[str, str] | | A dictionary with: `model` (required for `serverless_inference_api`), `url` (required for `inference_endpoints` or `text_generation_inference`), and other parameters like `timeout`, `headers`, `provider`. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token to use as HTTP bearer authorization. Check your HF token in your [account settings](https://huggingface.co/settings/tokens). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary with keyword arguments to customize text generation: `max_new_tokens`, `temperature`, `top_k`, `top_p`. See [Hugging Face documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation). | | `stop_words` | Optional[List[str]] | None | An optional list of strings representing the stop words. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------- | :------ | :----------------------------------------------------------------------- | | `prompt` | str | | A string representing the prompt. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) - [HuggingFaceAPIChatGenerator](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPIChatGenerator.mdx) --- ## HuggingFaceAPITextEmbedder Embed strings using Hugging Face APIs. :::info This component embeds plain text. To embed a list of documents, use `HuggingFaceAPIDocumentEmbedder`. ::: ## Key Features - Embeds text strings using Hugging Face APIs: free Serverless Inference API, paid Inference Endpoints, and self-hosted Text Embeddings Inference (TEI) - Use in query pipelines to embed user queries for semantic search - Returns a vector embedding of the input text ## Configuration 1. Drag the `HuggingFaceAPITextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the API type: `serverless_inference_api`, `inference_endpoints`, or `text_embeddings_inference`. 2. Enter the API parameters: for `serverless_inference_api`, enter the model ID; for `inference_endpoints` or `text_embeddings_inference`, enter the endpoint URL. 3. Enter your Hugging Face API token. Connect to your Hugging Face account first. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 4. Go to the **Advanced** tab to configure prefix, suffix, truncation, and normalization settings. ## Connections `HuggingFaceAPITextEmbedder` accepts a text string through its `text` input. It outputs the embedding as a list of floats (`embedding`). Connect the `Input` component's `query` output to this component's `text` input. Connect the `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`hugging_face_api_text_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/hugging_face_api_text_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml query_embedder: type: haystack.components.embedders.hugging_face_api_text_embedder.HuggingFaceAPITextEmbedder init_parameters: api_type: serverless_inference_api api_params: model: BAAI/bge-small-en-v1.5 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false truncate: true normalize: false ``` ### Using the component in a pipeline This query pipeline uses `HuggingFaceAPITextEmbedder` to embed a query and retrieve documents using semantic search: ```yaml # haystack-pipeline components: query_embedder: type: haystack.components.embedders.hugging_face_api_text_embedder.HuggingFaceAPITextEmbedder init_parameters: api_type: serverless_inference_api api_params: model: BAAI/bge-small-en-v1.5 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false prefix: suffix: truncate: true normalize: false embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding inputs: query: - query_embedder.text filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :------------- | | `text` | str | Text to embed. | ### Outputs | Parameter | Type | Description | | :---------- | :---------- | :------------------------------- | | `embedding` | List[float] | The embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------- | :---------------------------- | :------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_type` | Union[HFEmbeddingAPIType, str] | | The type of Hugging Face API to use. Options: `serverless_inference_api`, `inference_endpoints`, `text_embeddings_inference`. | | `api_params` | Dict[str, str] | | A dictionary containing either `model` (Hugging Face model ID, required for `serverless_inference_api`) or `url` (URL of the inference endpoint, required for `inference_endpoints` or `text_embeddings_inference`). | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token to use as HTTP bearer authorization. Check your HF token in your [account settings](https://huggingface.co/settings/tokens). | | `prefix` | str | | A string to add at the beginning of each text. | | `suffix` | str | | A string to add at the end of each text. | | `truncate` | Optional[bool] | True | Truncates the input text to the maximum length supported by the model. Applicable when `api_type` is `text_embeddings_inference` or `inference_endpoints` if the backend uses Text Embeddings Inference. Ignored for `serverless_inference_api`. | | `normalize` | Optional[bool] | False | Normalizes the embeddings to unit length. Applicable when `api_type` is `text_embeddings_inference` or `inference_endpoints` if the backend uses Text Embeddings Inference. Ignored for `serverless_inference_api`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Description | | :-------- | :--- | :------------- | | `text` | str | Text to embed. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) - [HuggingFaceAPIDocumentEmbedder](/docs/reference/pipeline-components/integrations/hugging-face/HuggingFaceAPIDocumentEmbedder.mdx) --- ## HuggingFaceLocalChatGenerator Generate chat responses using models from Hugging Face that run locally. ## Key Features - Chat generation using locally loaded Hugging Face models supporting the ChatML format - Supports popular models such as `HuggingFaceH4/zephyr-7b-beta` and `meta-llama/Llama-2-7b-chat-hf` - Streaming support for real-time token-by-token responses - Tool/function calling support with custom tool parsing - Configurable generation parameters and pipeline settings - Note: locally running LLMs may require powerful hardware depending on the model ## Configuration 1. Drag the `HuggingFaceLocalChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name or path (for example, `HuggingFaceH4/zephyr-7b-beta`). The model must support the ChatML messaging format. 2. Enter your Hugging Face API token for remote file authorization. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 3. Optionally, select a device for loading the model. If not set, the component selects the default device automatically. 4. Go to the **Advanced** tab to configure task type, chat template, generation kwargs, pipeline kwargs, stop words, streaming, tools, and other settings. ## Connections `HuggingFaceLocalChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input and outputs generated responses as `replies` (a list of `ChatMessage` instances). Connect `ChatPromptBuilder`'s `prompt` output to this component's `messages` input. Connect the `replies` output to `DeepsetAnswerBuilder` through `OutputAdapter`. ## Source Code To check this component's source code, open [`hugging_face_local.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/hugging_face_local.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceLocalChatGenerator: type: haystack.components.generators.chat.hugging_face_local.HuggingFaceLocalChatGenerator init_parameters: model: HuggingFaceH4/zephyr-7b-beta token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false ``` ### Using the Component in a Pipeline This is an example RAG pipeline with `HuggingFaceLocalChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false HuggingFaceLocalChatGenerator: type: haystack.components.generators.chat.hugging_face_local.HuggingFaceLocalChatGenerator init_parameters: model: HuggingFaceH4/zephyr-7b-beta task: device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false chat_template: generation_kwargs: huggingface_pipeline_kwargs: stop_words: streaming_callback: tools: tool_parsing_function: async_executor: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: HuggingFaceLocalChatGenerator.messages - sender: HuggingFaceLocalChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------- | | `messages` | List[ChatMessage] | | A list of ChatMessage objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, overrides the `tools` parameter provided during initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--------------- | :----------------------------------------------------------------- | | `replies` | List[ChatMessage] | A list containing the generated responses as ChatMessage instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------------------- | :------------------------------------------------------- | :------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | str | HuggingFaceH4/zephyr-7b-beta | The Hugging Face text generation model name or path (for example, `mistralai/Mistral-7B-Instruct-v0.2`). The model must be a chat model supporting the ChatML messaging format. If the model is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. | | `task` | Optional[Literal['text-generation', 'text2text-generation']] | None | The task for the Hugging Face pipeline. Options: `text-generation` (decoder models like GPT). If the task is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. | | `device` | Optional[ComponentDevice] | None | The device for loading the model. If `None`, automatically selects the default device. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The token to use as HTTP bearer authorization for remote files. | | `chat_template` | Optional[str] | None | An optional Jinja template for formatting chat messages. Most high-quality chat models have their own templates; use this only for models without a template or when you prefer a custom one. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary with keyword arguments to customize text generation: `max_length`, `max_new_tokens`, `temperature`, `top_k`, `top_p`. The only default is `max_new_tokens` set to 512. See [Hugging Face documentation](https://huggingface.co/docs/transformers/main/en/generation_strategies#customize-text-generation). | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | Dictionary with keyword arguments to initialize the Hugging Face pipeline. In case of duplication, these kwargs override `model`, `task`, `device`, and `token`. Can also include `model_kwargs`. See [Hugging Face pipeline documentation](https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.pipeline.task). | | `stop_words` | Optional[List[str]] | None | A list of stop words. If the model generates a stop word, the generation stops. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `tool_parsing_function` | Optional[Callable[[str], Optional[List[ToolCall]]]] | None | A callable that takes a string and returns a list of ToolCall objects or None. If None, the default tool parser is used. | | `async_executor` | Optional[ThreadPoolExecutor] | None | Optional ThreadPoolExecutor for async calls. If not provided, a single-threaded executor is initialized. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :--------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------ | | `messages` | List[ChatMessage] | | A list of ChatMessage objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## HuggingFaceTEIRanker Ranks documents based on their semantic similarity to the query. :::info Work in Progress Bear with us while we're working on adding pipeline examples and most common components connections. ::: ## Key Features - Ranks documents by semantic similarity to the query using a Text Embeddings Inference (TEI) API endpoint - Works with self-hosted TEI services and Hugging Face Inference Endpoints - Configurable number of returned documents with `top_k` - Built-in retry logic with configurable status codes - Optional truncation direction support ## Configuration 1. Drag the `HuggingFaceTEIRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the base URL of your TEI reranking service (for example, `https://api.example.com`). 2. Optionally, enter your Hugging Face API token if your TEI server requires authentication. Check your token in your [account settings](https://huggingface.co/settings/tokens). 3. Set `top_k` to control the maximum number of documents to return. 4. Go to the **Advanced** tab to configure raw scores, timeout, max retries, and retry status codes. ## Connections `HuggingFaceTEIRanker` accepts a `query` (str), a list of `Document` objects, and an optional `top_k` override and `truncation_direction`. It outputs a reranked list of `Document` objects. Connect a retriever's `documents` output and the query from `Input` to this component. Connect this component's `documents` output to the next stage in your pipeline (for example, a prompt builder or answer builder). ## Source Code To check this component's source code, open [`hugging_face_tei.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/hugging_face_tei.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceTEIRanker: type: haystack_integrations.components.rankers.huggingface_api.ranker.HuggingFaceTEIRanker init_parameters: {} ``` In a query pipeline, connect a retriever's `documents` output to the `documents` input, and connect the reranked `documents` output to a prompt builder or answer builder. ```yaml # haystack-pipeline components: HuggingFaceTEIRanker: type: haystack_integrations.components.rankers.huggingface_api.ranker.HuggingFaceTEIRanker init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :------------------- | :-------------------------- | :------ | :---------------------------------------------------------------- | | `query` | str | | The user query string to guide reranking. | | `documents` | List[Document] | | List of `Document` objects to rerank. | | `top_k` | Optional[int] | None | Optional override for the maximum number of documents to return. | | `truncation_direction` | Optional[TruncationDirection] | None | If set, enables text truncation in the specified direction. | ### Outputs | Parameter | Type | Description | | :-------- | :------------ | :---------------------------------- | | `documents` | List[Document] | A list of reranked documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------------- | :----------------- | :------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | str | | Base URL of the TEI reranking service (for example, "https://api.example.com"). | | `top_k` | int | 10 | Maximum number of top documents to return. | | `raw_scores` | bool | False | If True, include raw relevance scores in the API payload. | | `timeout` | Optional[int] | 30 | Request timeout in seconds. | | `max_retries` | int | 3 | Maximum number of retry attempts for failed requests. | | `retry_status_codes` | Optional[List[int]] | None | List of HTTP status codes that will trigger a retry. When None, HTTP 408, 418, 429 and 503 will be retried. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token to use as HTTP bearer authorization. Not always required depending on your TEI server configuration. Check your HF token in your [account settings](https://huggingface.co/settings/tokens). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :------------------- | :-------------------------- | :------ | :---------------------------------------------------------------- | | `query` | str | | The user query string to guide reranking. | | `documents` | List[Document] | | List of `Document` objects to rerank. | | `top_k` | Optional[int] | None | Optional override for the maximum number of documents to return. | | `truncation_direction` | Optional[TruncationDirection] | None | If set, enables text truncation in the specified direction. | ## Related Information - [Self-hosted Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference) - [Hugging Face Inference Endpoints](https://huggingface.co/inference-endpoints) --- ## JinaDocumentEmbedder Compute document embeddings using Jina AI models. ## Key Features - Computes embeddings for documents using [Jina AI](https://jina.ai/embeddings/) models. - Stores the embedding in each document's `embedding` field, making documents ready for semantic search and retrieval. - Supports multiple task types optimized for different use cases: `retrieval.passage`, `retrieval.query`, `text-matching`, `classification`, and `separation`. - Configurable batch size and progress bar for production deployments. - Supports late chunking for contextual chunk embeddings with `jina-embeddings-v3`. ## Configuration 1. Drag the `JinaDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Jina API key. Use `JINA_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [Jina AI](https://jina.ai/embeddings/). 2. Select the embedding model. Check available models on the [Jina documentation](https://jina.ai/embeddings/). 3. Set the `task` parameter to match your use case (for example, `retrieval.passage` for document passages). 4. Go to the **Advanced** tab to configure additional settings such as `batch_size`, `prefix`, `suffix`, `meta_fields_to_embed`, `dimensions`, `late_chunking`, and `embedding_separator`. ## Connections `JinaDocumentEmbedder` receives a list of documents through its `documents` input. It outputs the same documents with their embeddings added through its `documents` output, plus usage metadata through its `meta` output. Connect it after converters (such as `TextFileToDocument`, `HTMLToDocument`, or `MarkdownToDocument`) or after `DocumentSplitter` to embed chunks. Connect its `documents` output to `DocumentWriter` to store embedded documents in a document store. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/jina/src/haystack_integrations/components/embedders/jina/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml JinaDocumentEmbedder: type: haystack_integrations.components.embedders.jina.document_embedder.JinaDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-embeddings-v3 batch_size: 32 progress_bar: true task: retrieval.passage ``` This example shows an indexing pipeline that reads text files, splits them into chunks, embeds them using Jina, and writes them to an in-memory document store. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 100 split_overlap: 0 split_threshold: 0 splitting_function: JinaDocumentEmbedder: type: haystack_integrations.components.embedders.jina.document_embedder.JinaDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-embeddings-v3 batch_size: 32 progress_bar: true task: retrieval.passage DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: OVERWRITE document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: bm25_tokenization_regex: (?u)\b\w\w+\b bm25_algorithm: BM25L bm25_parameters: embedding_similarity_function: dot_product index: 'default' async_executor: connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: JinaDocumentEmbedder.documents - sender: JinaDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents, each with an `embedding` field containing the computed embedding. | | `meta` | Dict[str, Any] | A dictionary with metadata including the model name and usage statistics. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|-------------------|-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('JINA_API_KEY')|The Jina API key. | |model |str |jina-embeddings-v3 |The name of the Jina model to use. Check the list of available models on [Jina documentation](https://jina.ai/embeddings/). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |batch_size |int |32 |Number of Documents to encode at once. | |progress_bar |bool |True |Whether to show a progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. | |meta_fields_to_embed|Optional[List[str]]|None |List of meta fields that should be embedded along with the Document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the Document text. | |task |Optional[str] |None |The downstream task for which the embeddings will be used. The model will return the optimized embeddings for that task. Check the list of available tasks on [Jina documentation](https://jina.ai/embeddings/). | |dimensions |Optional[int] |None |Number of desired dimension. Smaller dimensions are easier to store and retrieve, with minimal performance impact thanks to MRL. | |late_chunking |Optional[bool] |None |A boolean to enable or disable late chunking. Apply the late chunking technique to leverage the model's long-context capabilities for generating contextual chunk embeddings. The support of `task` and `late_chunking` parameters is only available for jina-embeddings-v3.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------| |documents|List[Document]| |A list of Documents to embed.| --- ## JinaRanker Re-rank documents based on their relevance to a query using Jina AI reranker models. ## Key Features - Re-ranks documents by relevance to a query using [Jina AI](https://jina.ai/reranker/) cross-encoder models. - Improves retrieval quality by directly comparing query-document pairs. - Configurable `top_k` to limit the number of returned documents. - Configurable `score_threshold` to filter out low-relevance documents. ## Configuration 1. Drag the `JinaRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Jina API key. Use `JINA_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [Jina AI](https://jina.ai/reranker/). 2. Select the reranker model. Check available models on the [Jina documentation](https://jina.ai/reranker/). 3. Set `top_k` to control the number of documents returned. 4. Go to the **Advanced** tab to configure `score_threshold`. ## Connections `JinaRanker` accepts a query string through its `query` input, a list of documents through its `documents` input, and optional `top_k` and `score_threshold` overrides at runtime. It outputs ranked documents through its `documents` output, sorted from most to least relevant. Connect a Retriever's `documents` output to `JinaRanker`'s `documents` input. Then connect `JinaRanker`'s `documents` output to `PromptBuilder` or another component that uses ranked documents. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/jina/src/haystack_integrations/components/rankers/jina/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml JinaRanker: type: haystack_integrations.components.rankers.jina.ranker.JinaRanker init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-reranker-v1-base-en top_k: 3 ``` This example shows a RAG pipeline that retrieves documents, re-ranks them using Jina, and generates an answer. ```yaml # haystack-pipeline components: InMemoryBM25Retriever: type: haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever init_parameters: document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: bm25_tokenization_regex: (?u)\b\w\w+\b bm25_algorithm: BM25L bm25_parameters: embedding_similarity_function: dot_product index: 'default' async_executor: top_k: 10 JinaRanker: type: haystack_integrations.components.rankers.jina.ranker.JinaRanker init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-reranker-v1-base-en top_k: 3 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Given the following documents, answer the question.\n\nDocuments:\n{% for doc in documents %}{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true connections: - sender: InMemoryBM25Retriever.documents receiver: JinaRanker.documents - sender: JinaRanker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: AnswerBuilder.replies - sender: JinaRanker.documents receiver: AnswerBuilder.documents max_runs_per_component: 100 metadata: {} inputs: query: - InMemoryBM25Retriever.query - JinaRanker.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | Query string. | | `documents` | List[Document] | List of Documents. | | `top_k` | Optional[int] | The maximum number of Documents you want the Ranker to return. | | `score_threshold` | Optional[float] | If provided, only returns documents with a score above this threshold. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents most similar to the given query in descending order of similarity. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------|---------------|-----------------------------------|-------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('JINA_API_KEY')|The Jina API key. It can be explicitly provided or automatically read from the environment variable JINA_API_KEY (recommended).| |model |str |jina-reranker-v1-base-en |The name of the Jina model to use. Check the list of available models on `https://jina.ai/reranker/` | |top_k |Optional[int] |None |The maximum number of Documents to return per query. If `None`, all documents are returned | |score_threshold|Optional[float]|None |If provided only returns documents with a score above this threshold. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|---------------|-------|---------------------------------------------------------------------| |query |str | |Query string. | |documents |List[Document] | |List of Documents. | |top_k |Optional[int] |None |The maximum number of Documents you want the Ranker to return. | |score_threshold|Optional[float]|None |If provided only returns documents with a score above this threshold.| --- ## JinaTextEmbedder Embed strings, such as a user query, using Jina AI models. ## Key Features - Embeds a single text string (typically a query) using [Jina AI](https://jina.ai/embeddings/) models. - Use in query pipelines to convert user queries into embeddings for semantic search. - Supports multiple task types for optimized embeddings. - Configurable dimensions and late chunking for `jina-embeddings-v3`. - For embedding documents in indexes, use `JinaDocumentEmbedder` with the same model. ## Configuration 1. Drag the `JinaTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Jina API key. Use `JINA_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [Jina AI](https://jina.ai/embeddings/). 2. Select the embedding model. Use the same model as in `JinaDocumentEmbedder` in your indexing pipeline. 3. Set the `task` parameter. Use `retrieval.query` for search queries. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `dimensions`, and `late_chunking`. ## Connections `JinaTextEmbedder` accepts a string through its `text` input. It outputs the embedding as a list of floats through its `embedding` output, plus usage metadata through its `meta` output. Connect the `Input` component's `query` output to `JinaTextEmbedder`'s `text` input. Then connect `JinaTextEmbedder`'s `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/jina/src/haystack_integrations/components/embedders/jina/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml JinaTextEmbedder: type: haystack_integrations.components.embedders.jina.text_embedder.JinaTextEmbedder init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-embeddings-v3 task: retrieval.query ``` This example shows a query pipeline that embeds a user query using Jina and retrieves relevant documents. ```yaml # haystack-pipeline components: JinaTextEmbedder: type: haystack_integrations.components.embedders.jina.text_embedder.JinaTextEmbedder init_parameters: api_key: type: env_var env_vars: - JINA_API_KEY strict: false model: jina-embeddings-v3 task: retrieval.query InMemoryEmbeddingRetriever: type: haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever init_parameters: document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: bm25_tokenization_regex: (?u)\b\w\w+\b bm25_algorithm: BM25L bm25_parameters: embedding_similarity_function: dot_product index: 'default' async_executor: top_k: 5 connections: - sender: JinaTextEmbedder.embedding receiver: InMemoryEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - JinaTextEmbedder.text - InMemoryEmbeddingRetriever.query outputs: documents: InMemoryEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The string to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the input string. | | `meta` | Dict[str, Any] | A dictionary with metadata including the model name and usage statistics. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-------------|--------------|-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('JINA_API_KEY')|The Jina API key. It can be explicitly provided or automatically read from the environment variable `JINA_API_KEY` (recommended). | |model |str |jina-embeddings-v3 |The name of the Jina model to use. Check the list of available models on [Jina documentation](https://jina.ai/embeddings/). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |task |Optional[str] |None |The downstream task for which the embeddings will be used. The model will return the optimized embeddings for that task. Check the list of available tasks on [Jina documentation](https://jina.ai/embeddings/). | |dimensions |Optional[int] |None |Number of desired dimension. Smaller dimensions are easier to store and retrieve, with minimal performance impact thanks to MRL. | |late_chunking|Optional[bool]|None |A boolean to enable or disable late chunking. Apply the late chunking technique to leverage the model's long-context capabilities for generating contextual chunk embeddings. The support of `task` and `late_chunking` parameters is only available for jina-embeddings-v3.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|--------------------| |text |str | |The string to embed.| --- ## DocumentLanguageClassifier(Langdetect) Detect the language of each document and add it to the document's metadata. ## Key Features - Detects the language of document content using the [langdetect](https://github.com/Mimino666/langdetect) library. - Adds the detected language as a `language` field in each document's metadata. - Supports configurable list of target languages. - Documents with languages not in the configured list are labeled as `unmatched`. - Use with `MetadataRouter` to route documents to language-specific pipeline branches. ## Configuration 1. Drag the `DocumentLanguageClassifier` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `languages` to the list of ISO 639-1 language codes you want to support (for example, `["en", "de", "fr"]`). Documents not matching any language in this list will have their `language` metadata set to `unmatched`. ## Connections `DocumentLanguageClassifier` receives a list of documents and outputs the same documents with an added `language` metadata field. Connect it to a `MetadataRouter` to route documents to different processing branches based on their language. ## Source Code To check this component's source code, open [`document_language_classifier.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/langdetect/src/haystack_integrations/components/classifiers/langdetect/document_language_classifier.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml DocumentLanguageClassifier: type: haystack_integrations.components.classifiers.langdetect.document_language_classifier.DocumentLanguageClassifier init_parameters: languages: - en - de ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: DocumentLanguageClassifier: type: haystack_integrations.components.classifiers.langdetect.document_language_classifier.DocumentLanguageClassifier init_parameters: languages: - en metadata_router: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: en: field: meta.language operator: "==" value: en unmatched: field: meta.language operator: "==" value: unmatched document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: {} connections: - sender: DocumentLanguageClassifier.documents receiver: metadata_router.documents - sender: metadata_router.en receiver: document_writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to classify by language. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The input documents with `meta["language"]` set to the detected ISO 639-1 language code, or `"unmatched"` if the language is not in the configured list. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `languages` | Optional[List[str]] | `["en"]` | A list of ISO 639-1 language codes to recognize. Documents whose detected language is not in this list will have their `language` metadata set to `"unmatched"`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to classify by language. | ## Related Information - [TextLanguageRouter](/docs/reference/pipeline-components/integrations/langdetect/TextLanguageRouter.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## TextLanguageRouter Route text strings to different pipeline branches based on their detected language. ## Key Features - Detects the language of a text string using the [langdetect](https://github.com/Mimino666/langdetect) library. - Routes text to named output connections based on the detected language. - Supports configurable list of target languages. - Text in languages not in the configured list is routed to the `unmatched` output. - Useful for building multilingual query pipelines that need different processing per language. ## Configuration 1. Drag the `TextLanguageRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `languages` to the list of ISO 639-1 language codes you want to support (for example, `["en", "de"]`). Each language creates a separate named output connection. ## Connections `TextLanguageRouter` receives a text string and routes it to one of its named output connections based on the detected language. Each configured language gets its own named output; text that doesn't match goes to the `unmatched` output. Connect each output to the appropriate retriever or processing component for that language. ## Source Code To check this component's source code, open [`text_language_router.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/langdetect/src/haystack_integrations/components/routers/langdetect/text_language_router.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml TextLanguageRouter: type: haystack_integrations.components.routers.langdetect.text_language_router.TextLanguageRouter init_parameters: languages: - en - de ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: TextLanguageRouter: type: haystack_integrations.components.routers.langdetect.text_language_router.TextLanguageRouter init_parameters: languages: - en en_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: english-index connections: - sender: TextLanguageRouter.en receiver: en_retriever.query max_runs_per_component: 100 metadata: {} inputs: query: - TextLanguageRouter.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text string to route based on its detected language. | ### Outputs The outputs are dynamic and depend on the `languages` configured at initialization. There is one output per language (named with the ISO code), plus an `unmatched` output for text in other languages. | Parameter | Type | Description | | :-------- | :--- | :---------- | | `` | str | The input text, routed to the connection matching the detected language. | | `unmatched` | str | The input text, if its language is not in the configured list. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `languages` | Optional[List[str]] | `["en"]` | A list of ISO 639-1 language codes to route text to. Each code creates a named output connection. Text that doesn't match any configured language is routed to the `unmatched` output. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text string to detect language for and route. | ## Related Information - [DocumentLanguageClassifier](/docs/reference/pipeline-components/integrations/langdetect/DocumentLanguageClassifier.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## LangfuseConnector Trace your pipelines with Langfuse. ## Key Features - Integrates [Langfuse](https://langfuse.com) tracing into your pipelines without connecting to other components. - Automatically traces all pipeline operations when added to a pipeline. - Captures detailed information about pipeline runs, including API calls, context data, and prompts. - Supports custom invocation context to tag traces with run IDs, user IDs, or other metadata. - Configurable trace visibility: public or private. ## Configuration 1. Drag the `LangfuseConnector` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create secrets with your Langfuse keys. Use `LANGFUSE_SECRET_KEY` for the secret key and `LANGFUSE_PUBLIC_KEY` for the public key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API keys from [Langfuse](https://langfuse.com). 2. Enter a name for the trace. This name identifies the tracing run in the Langfuse dashboard. 3. Set `public` to control whether the tracing data is publicly accessible. 4. Go to the **Advanced** tab to configure `host`, `httpx_client`, `span_handler`, and `langfuse_client_kwargs`. For more information about setting up tracing with Langfuse, see [Trace with Langfuse](/docs/how-to-guides/productionizing-your-pipeline/trace-with-langfuse.mdx). ## Connections `LangfuseConnector` doesn't connect to any other components. Add it to your pipeline and it automatically traces all pipeline operations. It accepts an optional `invocation_context` input at runtime for adding per-run metadata to traces. It outputs `name`, `trace_url`, and `trace_id` values you can use to access tracing data. ## Source Code To check this component's source code, open [`langfuse_connector.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/langfuse/src/haystack_integrations/components/connectors/langfuse/langfuse_connector.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LangfuseConnector: type: haystack_integrations.components.connectors.langfuse.langfuse_connector.LangfuseConnector init_parameters: name: rag-chat public: false public_key: type: env_var env_vars: - LANGFUSE_PUBLIC_KEY strict: false secret_key: type: env_var env_vars: - LANGFUSE_SECRET_KEY strict: false ``` For more information about setting up tracing with Langfuse, see [Trace with Langfuse](/docs/how-to-guides/productionizing-your-pipeline/trace-with-langfuse.mdx). ## Connections `LangfuseConnector` doesn't connect to any other components. Add it to your pipeline and it automatically traces all pipeline operations when tracing is enabled. It accepts an optional `invocation_context` dictionary as input to attach additional metadata to each trace. It outputs the trace `name`, `trace_url`, and `trace_id`. This example shows a RAG pipeline with Langfuse tracing enabled. The `LangfuseConnector` is added to the pipeline but does not connect to other components — it automatically traces all pipeline operations. ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: "gpt-5" generation_kwargs: reasoning_effort: minimal verbosity: low answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true multi_file_converter: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: sources: - file_classifier.sources is_pipeline_async: false output_mapping: score_adder.output: documents pipeline: components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en score_adder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: | {%- set scored_documents = [] -%} {%- for document in documents -%} {%- set doc_dict = document.to_dict() -%} {%- set _ = doc_dict.update({'score': 100.0}) -%} {%- set scored_doc = document.from_dict(doc_dict) -%} {%- set _ = scored_documents.append(scored_doc) -%} {%- endfor -%} {{ scored_documents }} output_type: List[haystack.Document] custom_filters: unsafe: true text_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false tabular_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_joiner.documents receiver: splitter.documents - sender: text_converter.documents receiver: text_joiner.documents - sender: pdf_converter.documents receiver: text_joiner.documents - sender: markdown_converter.documents receiver: text_joiner.documents - sender: html_converter.documents receiver: text_joiner.documents - sender: pptx_converter.documents receiver: text_joiner.documents - sender: docx_converter.documents receiver: text_joiner.documents - sender: xlsx_converter.documents receiver: tabular_joiner.documents - sender: csv_converter.documents receiver: tabular_joiner.documents - sender: splitter.documents receiver: tabular_joiner.documents - sender: tabular_joiner.documents receiver: score_adder.documents LangfuseConnector: type: haystack_integrations.components.connectors.langfuse.langfuse_connector.LangfuseConnector init_parameters: name: rag-chat public: false public_key: type: env_var env_vars: - LANGFUSE_PUBLIC_KEY strict: false secret_key: type: env_var env_vars: - LANGFUSE_SECRET_KEY strict: false httpx_client: span_handler: host: langfuse_client_kwargs: connections: # Defines how the components are connected - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: llm.replies receiver: answer_builder.replies - sender: multi_file_converter.documents receiver: attachments_joiner.documents - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: prompt_builder.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" files: - multi_file_converter.sources outputs: # Defines the output of your pipeline documents: "attachments_joiner.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `invocation_context` | Optional[Dict[str, Any]] | A dictionary with additional context for the invocation. Useful for tagging traces with a run ID, user ID, or other metadata. These key-value pairs are visible in the Langfuse traces. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `name` | str | The name of the tracing component. | | `trace_url` | str | The URL to the tracing data. | | `trace_id` | str | The ID of the trace. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------------|------------------------|------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |name |str | |The name for the trace. This name will be used to identify the tracing run in the Langfuse dashboard. | |public |bool |False |Whether the tracing data should be public or private. If set to `True`, the tracing data will be publicly accessible to anyone with the tracing URL. If set to `False`, the tracing data will be private and only accessible to the Langfuse account owner. The default is `False`. | |public_key |Optional[Secret] |Secret.from_env_var('LANGFUSE_PUBLIC_KEY')|The Langfuse public key. Defaults to reading from LANGFUSE_PUBLIC_KEY environment variable. | |secret_key |Optional[Secret] |Secret.from_env_var('LANGFUSE_SECRET_KEY')|The Langfuse secret key. Defaults to reading from LANGFUSE_SECRET_KEY environment variable. | |httpx_client |Optional[httpx.Client] |None |Optional custom httpx.Client instance to use for Langfuse API calls. Note that when deserializing a pipeline from YAML, any custom client is discarded and Langfuse will create its own default client, since HTTPX clients cannot be serialized. | |span_handler |Optional[SpanHandler] |None |Optional custom handler for processing spans. If None, uses DefaultSpanHandler. The span handler controls how spans are created and processed, allowing customization of span types based on component types and additional processing after spans are yielded. See SpanHandler class for details on implementing custom handlers. host: Host of Langfuse API. Can also be set via `LANGFUSE_HOST` environment variable. By default it is set to `https://cloud.langfuse.com`.| |langfuse_client_kwargs|Optional[Dict[str, Any]]|None |Optional custom configuration for the Langfuse client. This is a dictionary containing any additional configuration options for the Langfuse client. See the Langfuse documentation for more details on available configuration options. | |host |Optional[str] |None | | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |------------------|------------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |invocation_context|Optional[Dict[str, Any]]|None |A dictionary with additional context for the invocation. This parameter is useful when users want to mark this particular invocation with additional information, e.g. a run id from their own execution framework, user id, etc. These key-value pairs are then visible in the Langfuse traces.| ## Related Information - [Trace with Langfuse](/docs/how-to-guides/productionizing-your-pipeline/trace-with-langfuse.mdx) --- ## LiteLLMChatGenerator Generate chat responses using any of 100+ LLM providers through [LiteLLM's](https://docs.litellm.ai/) unified interface. ## Key Features - Single component for access to OpenAI, Anthropic, Google, AWS Bedrock, Azure, Cohere, Mistral, Groq, and many more providers. - Uses LiteLLM's unified API format — no need to switch components when changing providers. - Model names use the LiteLLM format `provider/model-name` (for example, `anthropic/claude-sonnet-4-20250514`). - Accepts and returns messages in `ChatMessage` format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. ## Configuration 1. Drag the `LiteLLMChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` using LiteLLM format: `provider/model-name` (for example, `openai/gpt-4o` or `anthropic/claude-opus-4-5`). For the full list of supported providers and model names, see the [LiteLLM documentation](https://docs.litellm.ai/docs/providers). 2. Create a secret with the appropriate API key for your provider (for example, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`). For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `api_base_url`, and `tools`. ## Connections `LiteLLMChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/litellm/src/haystack_integrations/components/generators/litellm/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LiteLLMChatGenerator: type: haystack_integrations.components.generators.litellm.chat.chat_generator.LiteLLMChatGenerator init_parameters: model: openai/gpt-4o generation_kwargs: temperature: 0.7 max_tokens: 1024 ``` ### Using the Component with Different Providers ```yaml # Using Anthropic LiteLLMChatGenerator: type: haystack_integrations.components.generators.litellm.chat.chat_generator.LiteLLMChatGenerator init_parameters: model: anthropic/claude-opus-4-5 generation_kwargs: max_tokens: 2048 ``` ```yaml # Using AWS Bedrock LiteLLMChatGenerator: type: haystack_integrations.components.generators.litellm.chat.chat_generator.LiteLLMChatGenerator init_parameters: model: bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0 generation_kwargs: max_tokens: 1024 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: "Answer the following question: {{ question }}" llm: type: haystack_integrations.components.generators.litellm.chat.chat_generator.LiteLLMChatGenerator init_parameters: model: openai/gpt-4o-mini generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Optional[Secret] | None | The API key for the provider. Set the appropriate environment variable (for example, `OPENAI_API_KEY`) and use `Secret.from_env_var()`. | | `model` | str | `openai/gpt-4o` | The model to use in LiteLLM format: `provider/model-name`. See the [LiteLLM provider list](https://docs.litellm.ai/docs/providers). | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. | | `api_base_url` | Optional[str] | None | A custom API base URL for proxies or custom deployments. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters, such as `temperature`, `max_tokens`, and `top_p`. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for tool calling. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## LlamaCppChatGenerator Generate chat responses using LLMs run locally via [llama.cpp](https://github.com/ggml-org/llama.cpp). ## Key Features - Runs GGUF-format language models locally without requiring cloud API access. - Works on standard hardware, including machines without dedicated GPUs. - Accepts and returns messages in `ChatMessage` format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports multimodal models (text and image) through the LLaVA family and similar models. - Configurable context length and batch size. ## Configuration 1. Drag the `LlamaCppChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the path or URL of the GGUF model file to load (for example, `/path/to/mistral-7b.gguf`). 4. Go to the **Advanced** tab to configure `n_ctx`, `n_batch`, `model_kwargs`, `generation_kwargs`, and `streaming_callback`. ## Connections `LlamaCppChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/llama_cpp/src/haystack_integrations/components/generators/llama_cpp/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LlamaCppChatGenerator: type: haystack_integrations.components.generators.llama_cpp.LlamaCppChatGenerator init_parameters: model: /path/to/mistral-7b-instruct.gguf n_ctx: 4096 generation_kwargs: max_tokens: 1024 temperature: 0.7 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: "Answer the following question: {{ question }}" llm: type: haystack_integrations.components.generators.llama_cpp.LlamaCppChatGenerator init_parameters: model: /path/to/mistral-7b-instruct.gguf n_ctx: 4096 generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The path to the GGUF model file or a URL to download the model from. | | `n_ctx` | Optional[int] | 0 | The maximum context window size. Set to `0` to use the model's default. | | `n_batch` | Optional[int] | 512 | The number of tokens to process in parallel during evaluation. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the `llama_cpp.Llama` constructor. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Default generation parameters such as `max_tokens`, `temperature`, `top_p`, `top_k`, and `stop`. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for tool calling. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming token-by-token responses. | | `chat_handler_name` | Optional[str] | None | The name of a registered chat handler for multimodal models. | | `model_clip_path` | Optional[str] | None | The path to the CLIP model for multimodal (image + text) support. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## MetaLlamaChatGenerator Generates text using Meta's Llama models via the Llama API. ## Key Features - Generates text using models available on [Meta's Llama API](https://llama.developer.meta.com/docs/). - Supports streaming responses token by token. - Supports tool calling for agentic use cases. - Works seamlessly with `ChatPromptBuilder` for prompt construction. - Accepts any text generation parameters valid for the Llama Chat Completion API via `generation_kwargs`. :::note Response Format `MetaLlamaChatGenerator` currently only supports `json_schema` response format. ::: ## Configuration 1. Drag the `MetaLlamaChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Llama API key. Use `LLAMA_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select the model. For supported models, see [Llama API Docs](https://llama.developer.meta.com/docs/). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `streaming_callback`, `tools`, and `api_base_url`. ## Connections `MetaLlamaChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input. It outputs generated responses as a list of `ChatMessage` objects through its `replies` output. Connect `ChatPromptBuilder`'s `prompt` output to `MetaLlamaChatGenerator`'s `messages` input. Connect its `replies` output to `OutputAdapter` and then to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/meta_llama/src/haystack_integrations/components/generators/meta_llama/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MetaLlamaChatGenerator: type: haystack_integrations.components.generators.meta_llama.chat.chat_generator.MetaLlamaChatGenerator init_parameters: api_key: type: env_var env_vars: - LLAMA_API_KEY strict: false model: Llama-4-Scout-17B-16E-Instruct-FP8 api_base_url: https://api.llama.com/compat/v1/ ``` This is an example RAG pipeline with `MetaLlamaChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false MetaLlamaChatGenerator: type: haystack_integrations.components.generators.meta_llama.chat.chat_generator.MetaLlamaChatGenerator init_parameters: api_key: type: env_var env_vars: - LLAMA_API_KEY strict: false model: Llama-4-Scout-17B-16E-Instruct-FP8 api_base_url: https://api.llama.com/compat/v1/ generation_kwargs: streaming_callback: tools: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: MetaLlamaChatGenerator.messages - sender: MetaLlamaChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for the model. For details, see model documentation. | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of Tool objects or a Toolset that the model can use. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list containing the generated ChatMessage responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------------------|------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('LLAMA_API_KEY')|The Llama API key. | |model |str |Llama-4-Scout-17B-16E-Instruct-FP8 |The name of the Llama chat completion model to use. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | |api_base_url |Optional[str] |https://api.llama.com/compat/v1/ |The Llama API Base url. For more details, see LlamaAPI [docs](https://llama.developer.meta.com/docs/features/compatibility/). | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model. These parameters are all sent directly to the Llama API endpoint. See [Llama API docs](https://llama.developer.meta.com/docs/features/compatibility/) for more details. Some of the supported parameters: - `max_tokens`: The maximum number of tokens the output text can have. - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. - `safe_prompt`: Whether to inject a safety prompt before all conversations. - `random_seed`: The seed to use for random sampling.| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools for which the model can prepare calls. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |------------------|------------------------------------|-------|------------------------------------------------------------------------------------------------------------------------------| |messages |List[ChatMessage] | |A list of ChatMessage instances representing the input messages. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. | |generation_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments for the model. For details, see model documentation. | |tools |Optional[Union[List[Tool], Toolset]]|None |A list of Tool objects or a Toolset that the model can use. | --- ## MistralChatGenerator Generates text using Mistral's generative models through the Mistral API. ## Key Features - Generates text using [Mistral AI](https://docs.mistral.ai/platform/endpoints/) models via the Mistral Chat Completion API. - Supports streaming responses token by token. - Supports tool calling for agentic use cases. - Accepts any text generation parameters valid for the Mistral Chat Completion API via `generation_kwargs`. - Configurable timeout, retry behavior, and custom HTTP client. ## Configuration 1. Drag the `MistralChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Mistral API key. Use `MISTRAL_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Select the model. For supported models, see [Mistral AI docs](https://docs.mistral.ai/platform/endpoints/). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `streaming_callback`, `tools`, `timeout`, `max_retries`, `http_client_kwargs`, and `api_base_url`. ## Connections `MistralChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input. It outputs generated responses as a list of `ChatMessage` objects through its `replies` output. Connect `ChatPromptBuilder`'s `prompt` output to `MistralChatGenerator`'s `messages` input. Connect its `replies` output to `OutputAdapter` and then to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MistralChatGenerator: type: haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-small-latest api_base_url: https://api.mistral.ai/v1 ``` This is an example RAG pipeline with `MistralChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false MistralChatGenerator: type: haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-small-latest streaming_callback: api_base_url: https://api.mistral.ai/v1 generation_kwargs: tools: timeout: max_retries: http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: MistralChatGenerator.messages - sender: MistralChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the arguments you can use, see [Mistral API docs](https://docs.mistral.ai/api/). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set in pipeline configuration. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | | `tools_strict` | Optional[bool] | None | Whether to strictly enforce the tools provided in the `tools` parameter. If set to `True`, the model will only use the tools provided in the `tools` parameter. If set to `False`, the model can use other tools that are not provided in the `tools` parameter. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of `ChatMessage` objects representing the generated responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------------------|--------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('MISTRAL_API_KEY')|The Mistral API key. | |model |str |mistral-small-latest |The name of the Mistral chat completion model to use. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | |api_base_url |Optional[str] |https://api.mistral.ai/v1 |The Mistral API Base url. For more details, see Mistral [docs](https://docs.mistral.ai/api/). | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model. These parameters are all sent directly to the Mistral endpoint. See [Mistral API docs](https://docs.mistral.ai/api/) for more details. Some of the supported parameters: - `max_tokens`: The maximum number of tokens the output text can have. - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. - `safe_prompt`: Whether to inject a safety prompt before all conversations. - `random_seed`: The seed to use for random sampling.| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | |timeout |Optional[float] |None |The timeout for the Mistral API call. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]] |None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| | messages | List[ChatMessage] | |A list of `ChatMessage` objects representing the input messages. | | generation_kwargs | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the arguments you can use, see [Mistral API docs](https://docs.mistral.ai/api/).| | tools | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set in pipeline configuration. | | streaming_callback | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | |tools_strict | Optional[bool] | None | Whether to strictly enforce the tools provided in the `tools` parameter. If set to `True`, the model will only use the tools provided in the `tools` parameter. If set to `False`, the model can use other tools that are not provided in the `tools` parameter. | --- ## MistralDocumentEmbedder Embed documents using Mistral embedding models. ## Key Features - Embeds documents using [Mistral AI](https://mistral.ai/) embedding models. - Stores the embedding in each document's `embedding` field, ready for semantic search. - Use in indexing pipelines to embed documents before storing them in a document store. - Use the same embedding model as in `MistralTextEmbedder` in your query pipeline. - Configurable batch size and timeout for production use. ## Configuration 1. Drag the `MistralDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Mistral API key. Use `MISTRAL_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [Mistral AI](https://console.mistral.ai/). 2. Select the embedding model. 4. Go to the **Advanced** tab to configure `batch_size`, `prefix`, `suffix`, `meta_fields_to_embed`, `embedding_separator`, `timeout`, `max_retries`, and `http_client_kwargs`. ## Connections `MistralDocumentEmbedder` receives a list of documents through its `documents` input. It outputs the same documents with embeddings added through its `documents` output, plus usage metadata through its `meta` output. Connect a preprocessor (such as `DocumentSplitter`) output to `MistralDocumentEmbedder`'s `documents` input. Then connect its `documents` output to `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mistral/src/haystack_integrations/components/embedders/mistral/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MistralDocumentEmbedder: type: haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-embed batch_size: 32 ``` This example shows an indexing pipeline that embeds documents using Mistral before storing them in a document store. ```yaml # haystack-pipeline components: DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en MistralDocumentEmbedder: type: haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-embed batch_size: 32 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'mistral-embeddings' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE MultiFileConverter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 json_content_key: content connections: - sender: DocumentSplitter.documents receiver: MistralDocumentEmbedder.documents - sender: MistralDocumentEmbedder.documents receiver: DocumentWriter.documents - sender: MultiFileConverter.documents receiver: DocumentSplitter.documents max_runs_per_component: 100 metadata: {} inputs: files: - MultiFileConverter.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents with embeddings stored in the `embedding` field of each document. | | `meta` | Dict[str, Any] | Information about the usage of the model, including model name and token usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|------------------------|--------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('MISTRAL_API_KEY')|The Mistral API key. | |model |str |mistral-embed |The name of the model to use. | |api_base_url |Optional[str] |https://api.mistral.ai/v1 |The Mistral API Base url. For more details, see Mistral [docs](https://docs.mistral.ai/api/). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |batch_size |int |32 |Number of Documents to encode at once. | |progress_bar |bool |True |Whether to show a progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. | |meta_fields_to_embed|Optional[List[str]] |None |List of meta fields that should be embedded along with the Document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the Document text. | |timeout |Optional[float] |None |Timeout for Mistral client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact Mistral after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs |Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |documents|List[Document]| |A list of documents to embed.| --- ## MistralOCRDocumentConverter Extract text from documents using Mistral's OCR API, with optional structured annotations. ## Key Features - Extracts text from documents using Mistral's OCR model. - Accepts local files, URLs, and Mistral file IDs as input. - Automatically uploads local files to Mistral's file storage. - Outputs one Haystack Document per source, with all pages concatenated using form feed characters for accurate page-wise splitting. - Supports optional structured annotations using Pydantic schemas for bounding box and document-level analysis. - Returns both Haystack Documents and raw Mistral OCR API responses. ## Configuration 1. Drag the `MistralOCRDocumentConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Mistral API key. Use `MISTRAL_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `model`, `include_image_base64`, `pages`, and `cleanup_uploaded_files`. ## Connections `MistralOCRDocumentConverter` receives a list of file sources. It outputs a list of `Document` objects containing the extracted text and a list of raw API responses. ## Source Code To check this component's source code, open [`ocr_document_converter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mistral/src/haystack_integrations/components/converters/mistral/ocr_document_converter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MistralOCRDocumentConverter: type: haystack_integrations.components.converters.mistral.ocr_document_converter.MistralOCRDocumentConverter init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-ocr-2505 cleanup_uploaded_files: true ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: MistralOCRDocumentConverter: type: haystack_integrations.components.converters.mistral.ocr_document_converter.MistralOCRDocumentConverter init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-ocr-2505 document_splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: page split_length: 1 connections: - sender: MistralOCRDocumentConverter.documents receiver: document_splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream, ...]] | A list of file paths, URLs, `ByteStream` objects, or Mistral file identifiers to convert. Local files are automatically uploaded. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Metadata to add to all documents, or a list of metadata dicts (one per source). | | `bbox_annotation_schema` | Optional[Type[BaseModel]] | A Pydantic model schema for structured bounding box region annotations. | | `document_annotation_schema` | Optional[Type[BaseModel]] | A Pydantic model schema for structured document-level annotations. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The extracted text as Haystack Documents. Pages are separated by form feed characters (`\f`). | | `raw_mistral_response` | List[Dict[str, Any]] | The raw API responses from the Mistral OCR service for each input file. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("MISTRAL_API_KEY")` | The Mistral API key. | | `model` | str | `mistral-ocr-2505` | The Mistral OCR model to use. | | `include_image_base64` | bool | False | Whether to include base64-encoded images in the output. | | `pages` | Optional[List[int]] | None | A list of specific page numbers (0-indexed) to extract from multi-page documents. If not set, all pages are extracted. | | `image_limit` | Optional[int] | None | The maximum number of images to process per document. | | `image_min_size` | Optional[int] | None | The minimum image size (in pixels) to include in processing. | | `cleanup_uploaded_files` | bool | True | Whether to delete uploaded files from Mistral's storage after processing. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List | | A list of file paths or sources to convert. | | `meta` | Optional[Union[Dict, List[Dict]]] | None | Metadata to add to the resulting documents. | | `bbox_annotation_schema` | Optional[Type[BaseModel]] | None | Pydantic schema for bounding box annotations. | | `document_annotation_schema` | Optional[Type[BaseModel]] | None | Pydantic schema for document annotations. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## MistralTextEmbedder Embed strings, like user queries, using Mistral embedding models. ## Key Features - Embeds strings using [Mistral AI](https://mistral.ai/) embedding models. - Use in query pipelines to convert user queries into embeddings for semantic search. - For embedding documents in indexes, use `MistralDocumentEmbedder` with the same model. - Configurable timeout, retry behavior, and custom HTTP client. ## Configuration 1. Drag the `MistralTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Mistral API key. Use `MISTRAL_API_KEY` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [Mistral AI](https://console.mistral.ai/). 2. Select the embedding model. Use the same model as in `MistralDocumentEmbedder` in your indexing pipeline. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `timeout`, `max_retries`, and `http_client_kwargs`. ## Connections `MistralTextEmbedder` accepts a string through its `text` input. It outputs the embedding as a list of floats through its `embedding` output, plus usage metadata through its `meta` output. Connect the `Input` component's `query` output to `MistralTextEmbedder`'s `text` input. Then connect `MistralTextEmbedder`'s `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mistral/src/haystack_integrations/components/embedders/mistral/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MistralTextEmbedder: type: haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-embed ``` This example shows a query pipeline that embeds a user query using Mistral and retrieves relevant documents. ```yaml # haystack-pipeline components: MistralTextEmbedder: type: haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-embed EmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'mistral-embeddings' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 connections: - sender: MistralTextEmbedder.embedding receiver: EmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - MistralTextEmbedder.text - EmbeddingRetriever.query outputs: documents: EmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The string to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the input text. | | `meta` | Dict[str, Any] | Information about the usage of the model, including model name and token usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------|--------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('MISTRAL_API_KEY')|The Mistral API key. | |model |str |mistral-embed |The name of the Mistral embedding model to be used. | |api_base_url |Optional[str] |https://api.mistral.ai/v1 |The Mistral API Base url. For more details, see Mistral [docs](https://docs.mistral.ai/api/). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |timeout |Optional[float] |None |Timeout for Mistral client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact Mistral after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |text|str| |The string to embed.| --- ## MxbaiV2Ranker Ranks documents by their semantic similarity to the query using MxbaiRerank models. ## Key Features - Ranks documents by semantic similarity to the query using MxbaiRerank models. - Assigns similarity scores to each document. - Configurable `top_k` to limit the number of returned documents. - Configurable `score_threshold` to filter out low-relevance documents. - Supports custom model and tokenizer keyword arguments. ## Configuration 1. Drag the `MxbaiV2Ranker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the MxbaiRerank model to use for ranking. 2. Set `top_k` to control the number of documents returned. 4. Go to the **Advanced** tab to configure `max_length`, `meta_fields_to_embed`, `embedding_separator`, `score_threshold`, `batch_size`, `model_kwargs`, `tokenizer_kwargs`, and `disable_transformers_warnings`. ## Connections `MxbaiV2Ranker` accepts a query string through its `query` input and a list of documents through its `documents` input. It outputs the ranked documents through its `documents` output, sorted from most to least relevant. Connect a Retriever's `documents` output to `MxbaiV2Ranker`'s `documents` input. Then connect `MxbaiV2Ranker`'s `documents` output to `PromptBuilder` or use it as the pipeline's final output. ## Usage Examples ### Basic Configuration ```yaml MxbaiV2Ranker: type: deepset_cloud_custom_nodes.rankers.mxbai.mxbaiv2_ranker.MxbaiV2Ranker init_parameters: model: mixedbread-ai/mxbai-rerank-base-v2 top_k: 10 max_length: 8192 embedding_separator: \n disable_transformers_warnings: false batch_size: 16 ``` ### Using the Component in a Pipeline This is an example of a document search pipeline with hybrid retrieval, where the Ranker receives documents from both retrievers from `DocumentJoiner` and outputs the ranked documents as the final output of the pipeline. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' truncate: normalize_embeddings: false timeout: backend_kwargs: MxbaiV2Ranker: type: deepset_cloud_custom_nodes.rankers.mxbai.mxbaiv2_ranker.MxbaiV2Ranker init_parameters: model: mixedbread-ai/mxbai-rerank-base-v2 top_k: 10 max_length: 8192 meta_fields_to_embed: embedding_separator: \n score_threshold: disable_transformers_warnings: false model_kwargs: tokenizer_kwargs: batch_size: 16 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: DeepsetNvidiaTextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: document_joiner.documents receiver: MxbaiV2Ranker.documents max_runs_per_component: 100 metadata: {} inputs: query: - bm25_retriever.query - DeepsetNvidiaTextEmbedder.text - MxbaiV2Ranker.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: MxbaiV2Ranker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query used for ranking documents by their similarity to the query. | | `documents` | list[Document] | The documents to be ranked. | | `top_k` | Optional[int] | The maximum number of documents to return. | | `score_threshold` | Optional[float] | Returns only documents with the score above this threshold. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | list[Document] | The ranked documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |model|str | `mixedbread-ai/mxbai-rerank-base-v2`| The name of path to the model used for ranking.| |top_k|int|10|The maximum number of documents to return.| |max_length|int|8192|The maximum length of the input sequence.| |meta_fields_to_embed|List[str]|None|The list of metadata fields to include in the document embeddings.| |embedding_separator|str|\n|The separator to use between metadata fields and document content.| |score_threshold|float|None|The minimum score for documents to be included in the results.| |disable_transformers_warnings|bool|False|Whether to disable transformers warnings.| |model_kwargs|dict[str, Any]|None|Additional keyword arguments to pass to the model.| |tokenizer_kwargs|dict[str, Any]|None|Additional keyword arguments to pass to the tokenizer.| |batch_size|int|16|Batch size for processing documents.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default|Description| |---------------|---------------|-------|-----------| |query |str | | The query used for ranking documents by their similarity to the query. | |documents |list[Document] | | The documents to be ranked. | |top_k |Optional[int] |None | The maximum number of documents to return. | |score_threshold|Optional[float]|None | The minimum score for documents to be included in the results. | --- ## MongoDBAtlasEmbeddingRetriever Retrieves documents from the `MongoDBAtlasDocumentStore` by embedding similarity. This retriever is only compatible with the `MongoDBAtlasDocumentStore`. ## Key Features - Retrieves documents by comparing the query embedding against document embeddings stored in MongoDB Atlas. - Only compatible with `MongoDBAtlasDocumentStore`. - Configurable `top_k` to control the number of retrieved documents. - Supports runtime filter overrides with configurable `filter_policy` (`MERGE` or `REPLACE`). - Requires a text embedder (such as `SentenceTransformersTextEmbedder` or `MistralTextEmbedder`) to produce the query embedding. ## Configuration 1. Drag the `MongoDBAtlasEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Configure the `MongoDBAtlasDocumentStore` connection, including `mongo_connection_string`, `database_name`, `collection_name`, and `vector_search_index`. Create a secret with your MongoDB connection string using `MONGO_CONNECTION_STRING` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Set `top_k` to control the maximum number of documents returned. 4. Go to the **Advanced** tab to configure `filters` and `filter_policy`. ## Connections `MongoDBAtlasEmbeddingRetriever` accepts a query embedding (list of floats) through its `query_embedding` input, and optional `filters` and `top_k` overrides at runtime. It outputs retrieved documents through its `documents` output. Connect a text embedder's `embedding` output to `MongoDBAtlasEmbeddingRetriever`'s `query_embedding` input. Connect its `documents` output to a Ranker or directly to the pipeline output. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mongodb_atlas/src/haystack_integrations/components/retrievers/mongodb_atlas/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MongoDBAtlasEmbeddingRetriever: type: haystack_integrations.components.retrievers.mongodb_atlas.embedding_retriever.MongoDBAtlasEmbeddingRetriever init_parameters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore init_parameters: mongo_connection_string: type: env_var env_vars: - MONGO_CONNECTION_STRING strict: false database_name: my-db collection_name: my-collection vector_search_index: vector-search full_text_search_index: full-text-search embedding_field: embedding content_field: content ``` This is a document search pipeline that uses `MongoDBAtlasEmbeddingRetriever` to retrieve documents by embedding similarity, with `MistralTextEmbedder` to embed the query and `TransformersSimilarityRanker` to rank the documents. ```yaml # haystack-pipeline components: MistralTextEmbedder: type: haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder init_parameters: api_key: type: env_var env_vars: - MISTRAL_API_KEY strict: false model: mistral-embed MongoDBAtlasEmbeddingRetriever: type: haystack_integrations.components.retrievers.mongodb_atlas.embedding_retriever.MongoDBAtlasEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore init_parameters: mongo_connection_string: type: env_var env_vars: - MONGO_CONNECTION_STRING strict: false database_name: my-db collection_name: my-collection vector_search_index: vector-search full_text_search_index: full-text-search embedding_field: embedding content_field: content TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: cross-encoder/ms-marco-MiniLM-L-6-v2 device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false top_k: 10 query_prefix: '' document_prefix: '' meta_fields_to_embed: embedding_separator: \n scale_score: true calibration_factor: 1 score_threshold: model_kwargs: tokenizer_kwargs: batch_size: 16 connections: - sender: MistralTextEmbedder.embedding receiver: MongoDBAtlasEmbeddingRetriever.query_embedding - sender: MongoDBAtlasEmbeddingRetriever.documents receiver: TransformersSimilarityRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - MistralTextEmbedder.text - TransformersSimilarityRanker.query outputs: documents: TransformersSimilarityRanker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | Embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` configured for the retriever. | | `top_k` | Optional[int] | Maximum number of Documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents most similar to the given `query_embedding`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|-------------------------|--------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store|MongoDBAtlasDocumentStore| |An instance of MongoDBAtlasDocumentStore. | |filters |Optional[Dict[str, Any]] |None |Filters applied to the retrieved Documents. Make sure that the fields used in the filters are included in the configuration of the `vector_search_index`. You must configure them manually in the Web UI of MongoDB Atlas.| |top_k |int | 10|Maximum number of Documents to return. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied if they're configured for the component but also passed at runtime. Possible values: `MERGE` and `REPLACE`. `MERGE`: If both filter types target the same field, the runtime filter takes precedence. Logical filters are combined unly if they have the same operator (AND, OR). Comparison filters are combined using the default logical operator (defaults to AND). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding|List[float] | |Embedding of the query. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` configured for the retriever.| |top_k |Optional[int] |None |Maximum number of Documents to return. Overrides the value specified at initialization. | --- ## MongoDBAtlasFullTextRetriever Retrieves documents from the `MongoDBAtlasDocumentStore` by full-text search. This retriever is only compatible with the `MongoDBAtlasDocumentStore`. ## Key Features - Retrieves documents from MongoDB Atlas using full-text search. - Only compatible with `MongoDBAtlasDocumentStore`. - Supports single or multiple query strings. - Configurable fuzzy matching, match criteria (`any` or `all`), synonyms, and score customization. - Supports runtime filter overrides with configurable `filter_policy` (`MERGE` or `REPLACE`). - Relies on the `full_text_search_index` configured in `MongoDBAtlasDocumentStore`. ## Configuration 1. Drag the `MongoDBAtlasFullTextRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Configure the `MongoDBAtlasDocumentStore` connection, including `mongo_connection_string`, `database_name`, `collection_name`, and `full_text_search_index`. Create a secret with your MongoDB connection string using `MONGO_CONNECTION_STRING` as the secret key. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Set `top_k` to control the maximum number of documents returned. 4. Go to the **Advanced** tab to configure `filters` and `filter_policy`. ## Connections `MongoDBAtlasFullTextRetriever` accepts a query string (or list of strings) through its `query` input. It outputs retrieved documents through its `documents` output. Connect the `Input` component's `query` output to `MongoDBAtlasFullTextRetriever`'s `query` input. Connect its `documents` output to a Ranker or directly to the pipeline output. ## Source Code To check this component's source code, open [`full_text_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/mongodb_atlas/src/haystack_integrations/components/retrievers/mongodb_atlas/full_text_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MongoDBAtlasFullTextRetriever: type: haystack_integrations.components.retrievers.mongodb_atlas.full_text_retriever.MongoDBAtlasFullTextRetriever init_parameters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore init_parameters: mongo_connection_string: type: env_var env_vars: - MONGO_CONNECTION_STRING strict: false database_name: my-db collection_name: my-collection vector_search_index: vector-search full_text_search_index: full-text-search embedding_field: embedding content_field: content ``` This is a query pipeline with `MongoDBAtlasFullTextRetriever` that searches for documents in the `MongoDBAtlasDocumentStore`. ```yaml # haystack-pipeline components: TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: cross-encoder/ms-marco-MiniLM-L-6-v2 device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false top_k: 10 query_prefix: '' document_prefix: '' meta_fields_to_embed: embedding_separator: \n scale_score: true calibration_factor: 1 score_threshold: model_kwargs: tokenizer_kwargs: batch_size: 16 MongoDBAtlasFullTextRetriever: type: haystack_integrations.components.retrievers.mongodb_atlas.full_text_retriever.MongoDBAtlasFullTextRetriever init_parameters: filters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.mongodb_atlas.document_store.MongoDBAtlasDocumentStore init_parameters: mongo_connection_string: type: env_var env_vars: - MONGO_CONNECTION_STRING strict: false database_name: my-db collection_name: my-collection vector_search_index: vector-search full_text_search_index: full-text-search embedding_field: embedding content_field: content connections: - sender: MongoDBAtlasFullTextRetriever.documents receiver: TransformersSimilarityRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - TransformersSimilarityRanker.query - MongoDBAtlasFullTextRetriever.query outputs: documents: TransformersSimilarityRanker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | Union[str, List[str]] | The query string or a list of query strings to search for. If the query contains multiple terms, Atlas Search evaluates each term separately for matches. | | `fuzzy` | Optional[Dict[str, int]] | Enables finding strings similar to the search terms. Note that you can't use `fuzzy` with `synonyms`. Configurable options include `maxEdits`, `prefixLength`, and `maxExpansions`. For more details, refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields). | | `match_criteria` | Optional[Literal['any', 'all']] | Defines how terms in the query are matched. Supported options are `"any"` and `"all"`. For more details, refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields). | | `score` | Optional[Dict[str, Dict]] | Specifies the scoring method for matching results. Supported options include `boost`, `constant`, and `function`. For more details, refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields). | | `synonyms` | Optional[str] | The name of the synonym mapping definition in the index. This value cannot be an empty string. Note that you can't use `synonyms` with `fuzzy`. | | `filters` | Optional[Dict[str, Any]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` configured for the retriever. | | `top_k` | int | Maximum number of Documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of Documents most similar to the given `query`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|-------------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store|MongoDBAtlasDocumentStore| |An instance of MongoDBAtlasDocumentStore. | |filters |Optional[Dict[str, Any]] |None |Filters applied to the retrieved Documents. Make sure that the fields used in the filters are included in the configuration of the `full_text_search_index`. The configuration must be done manually in the Web UI of MongoDB Atlas.| |top_k |int | 10|Maximum number of Documents to return. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied if they're configured for the component but also passed at runtime. Possible values: `MERGE` and `REPLACE`. `MERGE`: If both filter types target the same field, the runtime filter takes precedence. Logical filters are combined unly if they have the same operator (AND, OR). Comparison filters are combined using the default logical operator (defaults to AND). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |--------------|-------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query |Union[str, List[str]] | |The query string or a list of query strings to search for. If the query contains multiple terms, Atlas Search evaluates each term separately for matches. | |fuzzy |Optional[Dict[str, int]] |None |Enables finding strings similar to the search terms. Note that you can't use `fuzzy` with `synonyms`. Configurable options include `maxEdits`, `prefixLength`, and `maxExpansions`. For more details refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields).| |match_criteria|Optional[Literal['any', 'all']]|None |Defines how terms in the query are matched. Supported options are `"any"` and `"all"`. For more details refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields). | |score |Optional[Dict[str, Dict]] |None |Specifies the scoring method for matching results. Supported options include `boost`, `constant`, and `function`. For more details refer to MongoDB Atlas [documentation](https://www.mongodb.com/docs/atlas/atlas-search/text/#fields). | |synonyms |Optional[str] |None |The name of the synonym mapping definition in the index. This value cannot be an empty string. Note that you can't use `synonyms` with `fuzzy`. | |filters |Optional[Dict[str, Any]] |None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` configured for the retriever. | |top_k |int |10 |Maximum number of Documents to return. | --- ## NvidiaChatGenerator Generates text using generative models hosted on NVIDIA's cloud or self-hosted with NVIDIA NIM. ## Key Features - Generates text using [NVIDIA generative models](https://build.nvidia.com/models). - Works with self-hosted models via NVIDIA NIM or models hosted on the NVIDIA API Catalog. - Supports streaming responses token by token. - Supports tool calling for agentic use cases. - Accepts any text generation parameters valid for the NVIDIA Chat Completion API via `generation_kwargs`. - Configurable timeout, retry behavior, and custom HTTP client. ## Configuration 1. Drag the `NvidiaChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Connect to your NVIDIA account on the Integrations page. For instructions, see [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx). 2. Select the model. For supported models, see [NVIDIA Docs](https://build.nvidia.com/models). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `streaming_callback`, `tools`, `timeout`, `max_retries`, `http_client_kwargs`, and `api_base_url`. ## Connections `NvidiaChatGenerator` accepts a list of `ChatMessage` objects through its `messages` input. It outputs generated responses as a list of `ChatMessage` objects through its `replies` output. Connect `ChatPromptBuilder`'s `prompt` output to `NvidiaChatGenerator`'s `messages` input. Connect its `replies` output to `OutputAdapter` and then to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/nvidia/src/haystack_integrations/components/generators/nvidia/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml NvidiaChatGenerator: type: haystack_integrations.components.generators.nvidia.chat.chat_generator.NvidiaChatGenerator init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: false model: meta/llama-3.1-8b-instruct ``` This is an example RAG pipeline with `NvidiaChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false NvidiaChatGenerator: type: haystack_integrations.components.generators.nvidia.chat.chat_generator.NvidiaChatGenerator init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: false model: meta/llama-3.1-8b-instruct api_base_url: generation_kwargs: streaming_callback: tools: timeout: max_retries: http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: NvidiaChatGenerator.messages - sender: NvidiaChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the arguments you can use, see [NVIDIA API docs](https://docs.nvcf.nvidia.com/ai/generative-models/). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set in pipeline configuration. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | | `tools_strict` | Optional[bool] | None | Whether to strictly enforce the tools provided in the `tools` parameter. If set to `True`, the model will only use the tools provided in the `tools` parameter. If set to `False`, the model can use other tools that are not provided in the `tools` parameter. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of `ChatMessage` objects representing the generated responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------------------|--------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('NVIDIA_API_KEY') |The NVIDIA API key. | |model |str |meta/llama-3.1-8b-instruct |The name of the NVIDIA chat completion model to use. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | |api_base_url |Optional[str] |os.getenv('NVIDIA_API_URL', DEFAULT_API_URL)|The NVIDIA API Base url. | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model. These parameters are all sent directly to the NVIDIA API endpoint. See [NVIDIA API docs](https://docs.nvcf.nvidia.com/ai/generative-models/) for more details. Some of the supported parameters: - `max_tokens`: The maximum number of tokens the output text can have. - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | |timeout |Optional[float] |None |The timeout for the NVIDIA API call. | |max_retries |Optional[int] |None |Maximum number of retries to contact NVIDIA after an internal error. If not set, it defaults to either the `NVIDIA_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]] |None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |messages |List[ChatMessage] | |A list of `ChatMessage` objects representing the input messages. | |generation_kwargs | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the arguments you can use, see [NVIDIA API docs](https://docs.nvcf.nvidia.com/ai/generative-models/).| |tools | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set in pipeline configuration. | |streaming_callback | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | |tools_strict | Optional[bool] | None | Whether to strictly enforce the tools provided in the `tools` parameter. If set to `True`, the model will only use the tools provided in the `tools` parameter. If set to `False`, the model can use other tools that are not provided in the `tools` parameter. | ## Related Information - [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx) --- ## NvidiaDocumentEmbedder Calculate document embeddings using NVIDIA models. Document embedders are used to embed documents in your indexes. ## Key Features - Embeds documents using NVIDIA models and stores the computed embedding in each document's `embedding` field. - Works with self-hosted models deployed with [NVIDIA NIM](https://ai.nvidia.com) or models hosted on the [NVIDIA API Catalog](https://build.nvidia.com/explore/discover). - Use in indexing pipelines to embed documents before storing them in a document store. - Use the same model as in `NvidiaTextEmbedder` in your query pipeline. - Configurable batch size, truncation, and progress bar. ## Configuration 1. Drag the `NvidiaDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Connect to your NVIDIA account on the Integrations page. For instructions, see [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx). 2. Select the embedding model. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `batch_size`, `progress_bar`, `meta_fields_to_embed`, `embedding_separator`, `truncate`, `timeout`, and `api_url`. ## Connections `NvidiaDocumentEmbedder` receives a list of documents through its `documents` input. It outputs the same documents with embeddings added through its `documents` output, plus usage metadata through its `meta` output. Connect a converter (such as `TextFileToDocument`) or `DocumentSplitter` output to `NvidiaDocumentEmbedder`'s `documents` input. Then connect its `documents` output to `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/nvidia/src/haystack_integrations/components/embedders/nvidia/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml NvidiaDocumentEmbedder: type: haystack_integrations.components.embedders.nvidia.document_embedder.NvidiaDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' batch_size: 32 progress_bar: true embedding_separator: "\n" ``` In this index, `NvidiaDocumentEmbedder` receives documents from `DocumentSplitter`, embeds them, and sends them to `DocumentWriter`. The index uses the `nvidia/nv-embedqa-e5-v5` model, so `NvidiaTextEmbedder` in the query pipeline must use the same model. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: NvidiaDocumentEmbedder: type: haystack_integrations.components.embedders.nvidia.document_embedder.NvidiaDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' batch_size: 32 progress_bar: true meta_fields_to_embed: embedding_separator: "\n" truncate: timeout: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: nvidia-embeddings-index max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: NvidiaDocumentEmbedder.documents - sender: NvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents with their embeddings added to the `embedding` field. | | `meta` | Dict[str, Any] | Metadata related to the embedding process, including usage statistics. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|-------------------------------------------|--------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Optional[str] |None |Embedding model to use. If no specific model along with locally hosted API URL is provided, the system defaults to the available model found using /models API. | |api_key |Optional[Secret] |Secret.from_env_var('NVIDIA_API_KEY') |API key for the NVIDIA NIM. | |api_url |str |os.getenv('NVIDIA_API_URL', DEFAULT_API_URL)|Custom API URL for the NVIDIA NIM. Format for API URL is `http://host:port` | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |batch_size |int |32 |Number of Documents to encode at once. Cannot be greater than 50. | |progress_bar |bool |True |Whether to show a progress bar or not. | |meta_fields_to_embed|Optional[List[str]] |None |List of meta fields that should be embedded along with the Document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the Document text. | |truncate |Optional[Union[EmbeddingTruncateMode, str]]|None |Specifies how inputs longer than the maximum token length should be truncated. If None the behavior is model-dependent, see the official documentation for more information.| |timeout |Optional[float] |None |Timeout for request calls, if not set it is inferred from the `NVIDIA_TIMEOUT` environment variable or set to 60 by default. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------| |documents|List[Document]| |A list of Documents to embed.| ## Related Information - [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx) --- ## NvidiaRanker Ranks documents by their semantic similarity to the query using NVIDIA NIM ranking models. ## Key Features - Ranks documents by semantic similarity to the query using [NVIDIA NIMs](https://ai.nvidia.com) ranking models. - Documents are ordered from most to least semantically relevant to the query. - Default model: `nvidia/nv-rerankqa-mistral-4b-v3`. - Configurable `top_k` to limit the number of returned documents. - Supports custom query and document prefixes. ## Configuration 1. Drag the `NvidiaRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Connect to your NVIDIA account on the Integrations page. For instructions, see [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx). 2. Select the ranking model. 3. Set `top_k` to control the number of documents returned. 4. Go to the **Advanced** tab to configure `truncate`, `query_prefix`, `document_prefix`, `meta_fields_to_embed`, `embedding_separator`, `timeout`, and `api_url`. ## Connections `NvidiaRanker` accepts a query string through its `query` input and a list of documents through its `documents` input, with an optional `top_k` override at runtime. It outputs ranked documents through its `documents` output, sorted from most to least relevant. Connect a Retriever's (or `DocumentJoiner`'s) `documents` output to `NvidiaRanker`'s `documents` input. Then connect its `documents` output to `PromptBuilder` or use it as the pipeline's final output. :::note `top_k` parameter In pipelines with both a retriever and a ranker, the `top_k` values are different. The retriever's `top_k` specifies how many documents it returns. The ranker then orders these documents. You can set the same or a smaller `top_k` value for the ranker. The ranker's `top_k` is the number of documents it returns (if it's the last component in the pipeline) or forwards to the next component. Adjusting the `top_k` values can help you optimize performance. A smaller `top_k` for the retriever means fewer documents to process for the ranker, which can speed up the pipeline. ::: ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/nvidia/src/haystack_integrations/components/rankers/nvidia/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml NvidiaRanker: type: haystack_integrations.components.rankers.nvidia.ranker.NvidiaRanker init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-rerankqa-mistral-4b-v3 api_url: https://integrate.api.nvidia.com/v1 top_k: 10 query_prefix: '' document_prefix: '' embedding_separator: "\n" ``` This is an example of a document search pipeline where `NvidiaRanker` receives joined documents from both a keyword and a semantic retriever and returns the ranked documents as the final result. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate NvidiaTextEmbedder: type: haystack_integrations.components.embedders.nvidia.text_embedder.NvidiaTextEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' truncate: timeout: NvidiaRanker: type: haystack_integrations.components.rankers.nvidia.ranker.NvidiaRanker init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-rerankqa-mistral-4b-v3 api_url: https://integrate.api.nvidia.com/v1 top_k: 10 truncate: query_prefix: '' document_prefix: '' meta_fields_to_embed: embedding_separator: "\n" timeout: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: NvidiaTextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: document_joiner.documents receiver: NvidiaRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - bm25_retriever.query - NvidiaTextEmbedder.text - NvidiaRanker.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: NvidiaRanker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query to rank the documents against. | | `documents` | List[Document] | The list of documents to rank. | | `top_k` | Optional[int] | The number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents most similar to the query in descending order of similarity. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|----------------------------------------|--------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Optional[str] |None |Ranking model to use. | |truncate |Optional[Union[RankerTruncateMode, str]]|None |Truncation strategy to use. Can be "NONE", "END", or RankerTruncateMode. Defaults to NIM's default. | |api_key |Optional[Secret] |Secret.from_env_var('NVIDIA_API_KEY') |API key for the NVIDIA NIM. | |api_url |str |os.getenv('NVIDIA_API_URL', DEFAULT_API_URL)|Custom API URL for the NVIDIA NIM. | |top_k |int |5 |Number of documents to return. | |query_prefix |str | |A string to add at the beginning of the query text before ranking. Use it to prepend the text with an instruction, as required by reranking models like `bge`. | |document_prefix |str | |A string to add at the beginning of each document before ranking. You can use it to prepend the document with an instruction, as required by embedding models like `bge`.| |meta_fields_to_embed|Optional[List[str]] |None |List of metadata fields to embed with the document. | |embedding_separator |str |\n |Separator to concatenate metadata fields to the document. | |timeout |Optional[float] |None |Timeout for request calls, if not set it is inferred from the `NVIDIA_TIMEOUT` environment variable or set to 60 by default. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|----------------------------------------| |query |str | |The query to rank the documents against.| |documents|List[Document]| |The list of documents to rank. | |top_k |Optional[int] |None |The number of documents to return. | ## Related Information - [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx) --- ## NvidiaTextEmbedder Embed strings, such as user queries, using NVIDIA models. ## Key Features - Embeds strings (typically user queries) using NVIDIA models for semantic search. - Works with self-hosted models deployed with [NVIDIA NIM](https://ai.nvidia.com) or models hosted on the [NVIDIA API Catalog](https://build.nvidia.com/explore/discover). - For models that differentiate between query and document inputs, this component embeds the input as a query. - Use in query pipelines to transform a query into a vector. - For embedding documents in indexes, use [`NvidiaDocumentEmbedder`](./NvidiaDocumentEmbedder.mdx). ## Configuration 1. Drag the `NvidiaTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Connect to your NVIDIA account on the Integrations page. For instructions, see [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx). 2. Select the embedding model. Use the same model as in `NvidiaDocumentEmbedder` in your indexing pipeline. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `truncate`, `timeout`, and `api_url`. ## Connections `NvidiaTextEmbedder` accepts a string through its `text` input. It outputs the embedding as a list of floats through its `embedding` output, plus usage metadata through its `meta` output. Connect the `Input` component's `query` output to `NvidiaTextEmbedder`'s `text` input. Then connect `NvidiaTextEmbedder`'s `embedding` output to an embedding retriever's `query_embedding` input. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/nvidia/src/haystack_integrations/components/embedders/nvidia/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml NvidiaTextEmbedder: type: haystack_integrations.components.embedders.nvidia.text_embedder.NvidiaTextEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' ``` This is an example of a query pipeline with `NvidiaTextEmbedder` that receives a query, embeds it, and sends it to `OpenSearchEmbeddingRetriever` to find matching documents. ```yaml # haystack-pipeline components: NvidiaTextEmbedder: type: haystack_integrations.components.embedders.nvidia.text_embedder.NvidiaTextEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' truncate: timeout: OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: nvidia-embeddings-index max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine connections: - sender: NvidiaTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - NvidiaTextEmbedder.text outputs: documents: OpenSearchEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | | `meta` | Dict[str, Any] | Metadata about the request, including usage statistics. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter| Type | Default | Description | |---------|-------------------------------------------|--------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |Optional[str] |None |Embedding model to use. If no specific model along with locally hosted API URL is provided, the system defaults to the available model found using /models API. | |api_key |Optional[Secret] |Secret.from_env_var('NVIDIA_API_KEY') |API key for the NVIDIA NIM. | |api_url |str |os.getenv('NVIDIA_API_URL', DEFAULT_API_URL)|Custom API URL for the NVIDIA NIM. Format for API URL is `http://host:port` | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |truncate |Optional[Union[EmbeddingTruncateMode, str]]|None |Specifies how inputs longer that the maximum token length should be truncated. If None the behavior is model-dependent, see the official documentation for more information.| |timeout |Optional[float] |None |Timeout for request calls, if not set it is inferred from the `NVIDIA_TIMEOUT` environment variable or set to 60 by default. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |The text to embed.| ## Related Information - [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx) --- ## OllamaChatGenerator Generate chat responses using models served with [Ollama](https://ollama.ai). ## Key Features - Works with any model available through Ollama, including Llama, Mistral, Qwen, and Gemma. - Accepts and returns messages in `ChatMessage` format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports structured output with JSON schema validation. - Supports reasoning with extended thinking (`think` parameter). ## Configuration 1. Drag the `OllamaChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Ollama model you want to use (for example, `llama3.2`). 2. Set the `url` to the address of your running Ollama server. The default is `http://localhost:11434`. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, `keep_alive`, and `response_format`. ## Connections `OllamaChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/generators/ollama/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaChatGenerator: type: haystack_integrations.components.generators.ollama.chat.chat_generator.OllamaChatGenerator init_parameters: model: llama3.2 url: http://localhost:11434 generation_kwargs: temperature: 0.7 timeout: 120 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: | Answer the following question: {{ question }} llm: type: haystack_integrations.components.generators.ollama.chat.chat_generator.OllamaChatGenerator init_parameters: model: llama3.2 url: http://localhost:11434 timeout: 120 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `qwen3:0.6b` | The name of the Ollama model to use. Run `ollama list` to see available models. | | `url` | str | `http://localhost:11434` | The URL of the Ollama API server. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional parameters for text generation, such as `temperature`, `top_k`, `top_p`, and `num_predict`. | | `timeout` | int | 120 | Request timeout in seconds. | | `max_retries` | int | 0 | Maximum number of retries on failed requests. | | `keep_alive` | Optional[Union[float, str]] | None | Controls how long the model stays loaded in memory after the last request. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for tool calling. | | `response_format` | Optional[Union[Literal["json"], Dict]] | None | Forces a specific response format. Set to `"json"` for JSON output or provide a JSON schema. | | `think` | Union[bool, Literal["low", "medium", "high"]] | False | Enables extended reasoning. Set to `True` or a verbosity level string for reasoning models. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model, overriding init-time tools. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## OllamaDocumentEmbedder Compute embeddings for a list of documents using embedding models served with [Ollama](https://ollama.ai). Use this component in indexing pipelines to prepare documents for embedding-based retrieval. ## Key Features - Works with any embedding model available through Ollama. - Stores the computed embedding in each document's `embedding` field. - Supports adding a prefix and suffix to document text before embedding. - Allows embedding metadata fields alongside document content. - Processes documents in configurable batches. ## Configuration 1. Drag the `OllamaDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to an embedding model available on your Ollama server (for example, `nomic-embed-text`). 2. Set the `url` to your Ollama server address. The default is `http://localhost:11434`. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `batch_size`, `meta_fields_to_embed`, and `embedding_separator`. ## Connections `OllamaDocumentEmbedder` receives a list of documents, typically from a document splitter or converter. It outputs the same documents with embeddings added to their `embedding` field, ready to be sent to a `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/embedders/ollama/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaDocumentEmbedder: type: haystack_integrations.components.embedders.ollama.document_embedder.OllamaDocumentEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 batch_size: 32 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: OllamaDocumentEmbedder: type: haystack_integrations.components.embedders.ollama.document_embedder.OllamaDocumentEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 batch_size: 32 meta_fields_to_embed: embedding_separator: "\n" document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 connections: - sender: OllamaDocumentEmbedder.documents receiver: document_writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents with their `embedding` field populated. | | `meta` | Dict[str, Any] | Metadata about the embedding request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `nomic-embed-text` | The name of the Ollama embedding model to use. | | `url` | str | `http://localhost:11434` | The URL of the Ollama API server. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional parameters for the embedding request. | | `timeout` | int | 120 | Request timeout in seconds. | | `keep_alive` | Optional[Union[float, str]] | None | Controls how long the model stays loaded in memory. | | `prefix` | str | `""` | A string to add at the beginning of each document's text before embedding. | | `suffix` | str | `""` | A string to add at the end of each document's text before embedding. | | `progress_bar` | bool | True | Whether to show a progress bar during embedding. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text before embedding. | | `embedding_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | | `batch_size` | int | 32 | The number of documents to process in each batch. | | `dimensions` | Optional[int] | None | The number of dimensions in the output embedding, if supported by the model. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to embed. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## OllamaTextEmbedder Embed strings using embedding models served with [Ollama](https://ollama.ai). Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Works with any embedding model available through Ollama. - Outputs a float vector embedding suitable for use with embedding retrievers. - The embedding model must match the one used by `OllamaDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `OllamaTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the same embedding model used in your indexing pipeline (for example, `nomic-embed-text`). 2. Set the `url` to your Ollama server address. The default is `http://localhost:11434`. 4. Go to the **Advanced** tab to configure `timeout`, `keep_alive`, and `dimensions`. ## Connections `OllamaTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever such as `OpenSearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/embedders/ollama/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaTextEmbedder: type: haystack_integrations.components.embedders.ollama.text_embedder.OllamaTextEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 timeout: 120 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: OllamaTextEmbedder: type: haystack_integrations.components.embedders.ollama.text_embedder.OllamaTextEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 timeout: 120 OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 connections: - sender: OllamaTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - OllamaTextEmbedder.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | | `meta` | Dict[str, Any] | Metadata about the request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `nomic-embed-text` | The name of the Ollama embedding model to use. | | `url` | str | `http://localhost:11434` | The URL of the Ollama API server. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional parameters for the embedding request. | | `timeout` | int | 120 | Request timeout in seconds. | | `keep_alive` | Optional[Union[float, str]] | None | Controls how long the model stays loaded in memory. | | `dimensions` | Optional[int] | None | The number of dimensions in the output embedding, if supported by the model. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text to embed. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## OpenAIDocumentEmbedder Compute document embeddings using OpenAI models. Use this component in indexes to embed documents before storing them in a vector database. ## Key Features - Computes dense vector embeddings for documents using OpenAI embedding models. - Supports all OpenAI embedding models, including the `text-embedding-3` series. - Embeds documents in configurable batch sizes for efficient processing. - Optionally embeds metadata fields along with document content. - Configurable error handling: raises or logs errors on failure. ## Configuration 1. Drag the `OpenAIDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Make sure is connected to your OpenAI account. For help, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - Select the embedding model to use. 4. Go to the **Advanced** tab to configure additional settings such as `timeout`, `max_retries`, `http_client_kwargs`, `prefix`, `suffix`, and metadata embedding options. ## Connections `OpenAIDocumentEmbedder` receives documents to embed from PreProcessors like `DocumentSplitter`. It sends the embedded documents to `DocumentWriter`, which writes them into a document store. ## Source Code To check this component's source code, open [`openai_document_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/openai_document_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml document_embedder: type: haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: text-embedding-ada-002 ``` This is an index that uses `OpenAIDocumentEmbedder` to embed documents before storing them: ```yaml # haystack-pipeline components: document_embedder: type: haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: text-embedding-ada-002 document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false index: my_index embedding_dim: 1536 connections: - sender: document_embedder.documents receiver: document_writer.documents inputs: documents: - document_embedder.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents with embeddings. | | `meta` | Dict[str, Any] | Information about the usage of the model, including model name and token usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|------------------------|-------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('OPENAI_API_KEY')|The OpenAI API key. You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter during initialization. | |model |str |text-embedding-ada-002 |The name of the model to use for calculating embeddings. The default model is `text-embedding-ada-002`. | |dimensions |Optional[int] |None |The number of dimensions of the resulting embeddings. Only `text-embedding-3` and later models support this parameter. | |api_base_url |Optional[str] |None |Overrides the default base URL for all HTTP requests. | |organization |Optional[str] |None |Your OpenAI organization ID. See OpenAI's [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) for more information. | |prefix |str |"" |A string to add at the beginning of each text. | |suffix |str |"" |A string to add at the end of each text. | |batch_size |int |32 |Number of documents to embed at once. | |progress_bar |bool |True |If `True`, shows a progress bar when running. | |meta_fields_to_embed|Optional[List[str]] |None |List of metadata fields to embed along with the document text. | |embedding_separator |str |\n |Separator used to concatenate the metadata fields to the document text. | |timeout |Optional[float] |None |Timeout for OpenAI client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or 5 retries. | |http_client_kwargs |Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | |raise_on_failure |bool |False |Whether to raise an exception if the embedding request fails. If `False`, the component will log the error and continue processing the remaining documents. If `True`, it will raise an exception on failure.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------| |documents|List[Document]| |A list of documents to embed.| ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## OpenAIResponsesChatGenerator Generate text with LLM models using OpenAI's Responses API with support for reasoning models. The default model is `gpt-5-mini`. The Responses API is designed for models that can reason. It supports features like reasoning summaries, multi-turn conversations with previous response IDs, and structured outputs. ## Key Features - Uses OpenAI's Responses API, optimized for reasoning models (gpt-4, gpt-5, o-series). - Supports reasoning configuration with `effort` and `summary` parameters. - Supports multi-turn conversations using `previous_response_id`. - Supports structured output via Pydantic models (`text_format`) or JSON schema (`text`). - Supports tool calling with Haystack tools, Toolsets, and OpenAI/MCP tool definitions. - Streaming support for token-by-token responses. ## Supported Models The following OpenAI models are available in the platform: | Model | Notes | | :---- | :---- | | GPT-5.6 Sol | Latest GPT-5.6 variant. Supports `reasoning_effort` values: `none`, `low`, `medium`, `high`, `xhigh`, `max`. | | GPT-5.6 Terra | Latest GPT-5.6 variant. Supports `reasoning_effort` values: `none`, `low`, `medium`, `high`, `xhigh`, `max`. | | GPT-5.6 Luna | Latest GPT-5.6 variant. Supports `reasoning_effort` values: `none`, `low`, `medium`, `high`, `xhigh`, `max`. | | GPT-5.5 | Supports `reasoning_effort` values: `none`, `low`, `medium`, `high`, `xhigh`. | | GPT-5.5 Pro | Supports `reasoning_effort` values: `none`, `low`, `medium`, `high`, `xhigh`. | | GPT-5.4 | — | | GPT-5.4 Pro | — | | GPT-5.4 mini | — | | GPT-5.4 nano | — | | GPT-5.2 | — | | GPT-5.2 Pro | — | | GPT-5.1 | — | | GPT-5 | — | | GPT-5 Pro | — | | GPT-5 mini | — | | GPT-5 nano | — | | GPT-4.1 | — | | GPT-4.1 mini | — | | GPT-4.1 nano | — | | GPT-4o | — | | GPT-4o mini | — | | GPT-3.5 Turbo | — | | GPT-3.5 Turbo 16k | — | ## Configuration 1. Drag the `OpenAIResponsesChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Make sure is connected to your OpenAI account. For help, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - Select the model to use. 4. Go to the **Advanced** tab to configure additional settings such as `generation_kwargs`, `timeout`, `max_retries`, `http_client_kwargs`, and tool options. ## Connections `OpenAIResponsesChatGenerator` receives rendered chat prompts from `ChatPromptBuilder` through its `messages` input. It sends generated replies through its `replies` output to downstream components such as `OutputAdapter` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`openai_responses.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/openai_responses.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml openai_responses_chat_generator: type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: reasoning: effort: low summary: auto temperature: 0.7 max_tokens: 500 ``` This is an example RAG pipeline with `OpenAIResponsesChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 chat_prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering questions based on the provided documents.\nIf the documents don't contain the answer, say so.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user openai_responses_chat_generator: type: haystack.components.generators.chat.openai_responses.OpenAIResponsesChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: reasoning: effort: low summary: auto temperature: 0.7 max_tokens: 500 output_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: chat_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: chat_prompt_builder.prompt receiver: openai_responses_chat_generator.messages - sender: openai_responses_chat_generator.replies receiver: output_adapter.replies - sender: output_adapter.output receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - chat_prompt_builder.query - answer_builder.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents answers: answer_builder.answers metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of ChatMessage objects representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses/create). | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]] | A list of tools or OpenAI/MCP tool definitions for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization. Can accept either a list of `Tool` objects, or OpenAI/MCP tool definitions as dictionaries. You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | Optional[bool] | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows the schema exactly, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------------- | :---------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | The OpenAI API key. Set it on the Integrations page. | | `model` | str | gpt-5-mini | The name of the model to use. For a list of available models, see the [Supported Models](#supported-models) section above. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk) as an argument. | | `api_base_url` | Optional[str] | None | An optional base URL. | | `organization` | Optional[str] | None | Your organization ID. See [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses) for more details. Some supported parameters: `temperature` (sampling temperature, higher values mean more risks), `top_p` (nucleus sampling probability mass), `previous_response_id` (ID of the previous response for multi-turn conversations), `text_format` (Pydantic model for structured outputs), `text` (JSON schema for structured outputs), `reasoning` (dictionary with `effort`, `summary`, `generate_summary`, and `mode` parameters for reasoning models; `mode` can be `standard` or `pro` and is supported since GPT-5.6), `include` (additional output data to include in the model response, such as `web_search_call.action.sources`, `code_interpreter_call.outputs`, `file_search_call.results`, `message.output_text.logprobs`, and `reasoning.encrypted_content`). You can also use these flattened convenience parameters, which the component maps to the nested OpenAI API format: `reasoning_effort` (maps to `reasoning.effort`; for GPT-5.6 models, supports `none`, `low`, `medium`, `high`, `xhigh`, and `max`), `reasoning_summary` (maps to `reasoning.summary`; values include `auto`, `concise`, and `detailed`), `reasoning_mode` (maps to `reasoning.mode`), `include_reasoning_encrypted_content` (when set to `true`, adds `reasoning.encrypted_content` to `include`), and `verbosity` (maps to `text.verbosity`). | | `timeout` | Optional[float] | 30.0 | Timeout for OpenAI client calls. If not set, it defaults to the `OPENAI_TIMEOUT` environment variable or 30 seconds. | | `max_retries` | Optional[int] | five | Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to the `OPENAI_MAX_RETRIES` environment variable or five. | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]]| None | A list of tools, a Toolset, or OpenAI/MCP tool definitions for which the model can prepare calls. This parameter can accept either a list of `Tool` objects, a `Toolset` instance, or OpenAI/MCP tool definitions as dictionaries. Note: You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | boolean | False | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. In Response API, tool calls are strict by default. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :------------------- | :---------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses/create). | | `tools` | Optional[Union[List[Tool], Toolset, List[dict]]]| None | A list of tools, a Toolset, or OpenAI/MCP tool definitions for which the model can prepare calls. If set, it overrides the `tools` parameter in pipeline configuration. Can accept either a list of `Tool` objects, a `Toolset` instance, or OpenAI/MCP tool definitions as dictionaries. Note: You cannot pass OpenAI/MCP tools and Haystack tools together. | | `tools_strict` | Optional[bool] | None | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) - [LLM](/docs/reference/pipeline-components/ai/LLM.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## OpenAITextEmbedder Embed strings, such as user queries, using OpenAI models. Use this component in query pipelines when you want to perform semantic search. ## Key Features - Embeds text strings (queries) using OpenAI embedding models. - Supports all OpenAI embedding models, including the `text-embedding-3` series. - Outputs the embedding for use with embedding-based retrievers. - Supports configurable prefix and suffix for text preprocessing. ## Configuration 1. Drag the `OpenAITextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Make sure is connected to your OpenAI account. For help, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - Select the embedding model to use. 4. Go to the **Advanced** tab to configure additional settings such as `timeout`, `max_retries`, `http_client_kwargs`, `prefix`, and `suffix`. ## Connections `OpenAITextEmbedder` receives text to embed from the `Input` component. It sends the embedding to embedding-based retrievers like `OpenSearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`openai_text_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/openai_text_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml OpenAITextEmbedder: type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: text-embedding-ada-002 prefix: '' suffix: '' ``` This is a query pipeline that uses `OpenAITextEmbedder` to embed a query and retrieve documents: ```yaml # haystack-pipeline components: embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false timeout: top_k: 20 OpenAITextEmbedder: type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: text-embedding-ada-002 dimensions: api_base_url: organization: prefix: '' suffix: '' timeout: max_retries: http_client_kwargs: connections: - sender: OpenAITextEmbedder.embedding receiver: embedding_retriever.query_embedding inputs: query: - OpenAITextEmbedder.text filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | Text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the input text. | | `meta` | Dict[str, Any] | Information about the usage of the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------|-------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('OPENAI_API_KEY')|The OpenAI API key. You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter during initialization. | |model |str |text-embedding-ada-002 |The name of the model to use for calculating embeddings. The default model is `text-embedding-ada-002`. | |dimensions |Optional[int] |None |The number of dimensions of the resulting embeddings. Only `text-embedding-3` and later models support this parameter. | |api_base_url |Optional[str] |None |Overrides default base URL for all HTTP requests. | |organization |Optional[str] |None |Your organization ID. See OpenAI's [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization) for more information. | |prefix |str | |A string to add at the beginning of each text to embed. | |suffix |str | |A string to add at the end of each text to embed. | |timeout |Optional[float] |None |Timeout for OpenAI client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|--------------| |text |str | |Text to embed.| ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## OpenRouterChatGenerator Generate text using large language models hosted on OpenRouter. For a list of supported models, see [OpenRouter documentation](https://openrouter.ai/models). ## Key Features - Supports all models available through the OpenRouter API. - Accepts all parameters supported by the OpenRouter chat completion endpoint via `generation_kwargs`. - Supports tool calling with Haystack tools and Toolsets. - Supports streaming responses token by token. ## Configuration 1. Drag the `OpenRouterChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your OpenRouter account by creating a secret called `OPENROUTER_API_KEY`. For more information about secrets, see [Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Select the model to use. 4. Go to the **Advanced** tab to configure additional settings such as `generation_kwargs`, `timeout`, `max_retries`, `http_client_kwargs`, `extra_headers`, and tool options. ## Connections `OpenRouterChatGenerator` receives rendered chat prompts from `ChatPromptBuilder` through its `messages` input. It sends generated replies through its `replies` output to downstream components such as `OutputAdapter` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/openrouter/src/haystack_integrations/components/generators/openrouter/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenRouterChatGenerator: type: haystack_integrations.components.generators.openrouter.chat.chat_generator.OpenRouterChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENROUTER_API_KEY strict: false model: openai/gpt-4o-mini api_base_url: https://openrouter.ai/api/v1 ``` This is an example RAG pipeline with `OpenRouterChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false OpenRouterChatGenerator: type: haystack_integrations.components.generators.openrouter.chat.chat_generator.OpenRouterChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENROUTER_API_KEY strict: false model: openai/gpt-4o-mini api_base_url: https://openrouter.ai/api/v1 generation_kwargs: streaming_callback: tools: timeout: extra_headers: max_retries: http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: OpenRouterChatGenerator.messages - sender: OpenRouterChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For a list of supported parameters, see [OpenRouter documentation](https://openrouter.ai/docs/quickstart). | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tools or a Toolset for which the model can prepare calls. If set, it will override the `tools` parameter set during component initialization. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | | `tools_strict` | Optional[bool] | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------------------|-----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('OPENROUTER_API_KEY')|The OpenRouter API key. | |model |str |openai/gpt-4o-mini |The name of the OpenRouter chat completion model to use. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | |api_base_url |Optional[str] |https://openrouter.ai/api/v1 |The OpenRouter API Base url. For more details, see OpenRouter [docs](https://openrouter.ai/docs/quickstart). | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model. These parameters are all sent directly to the OpenRouter endpoint. See [OpenRouter API docs](https://openrouter.ai/docs/quickstart) for more details. Some of the supported parameters: - `max_tokens`: The maximum number of tokens the output text can have. - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. - `safe_prompt`: Whether to inject a safety prompt before all conversations. - `random_seed`: The seed to use for random sampling.| |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | |timeout |Optional[float] |None |The timeout for the OpenRouter API call. | |extra_headers |Optional[Dict[str, Any]] |None |Additional HTTP headers to include in requests to the OpenRouter API. This can be useful for adding site URL or title for rankings on openrouter.ai For more details, see OpenRouter [docs](https://openrouter.ai/docs/quickstart). | |max_retries |Optional[int] |None |Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]] |None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |------------------|------------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |List[ChatMessage] | |A list of ChatMessage instances representing the input messages. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. | |generation_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For a list of supported parameters, see [OpenRouter documentation](https://openrouter.ai/docs/quickstart). | |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. If set, it will override the `tools` parameter set during component initialization. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | |tools_strict |Optional[bool] |None |Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration.| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## OpenSearchBM25Retriever Retrieve documents from an `OpenSearchDocumentStore` using the keyword-based BM25 algorithm. ## Key Features - Keyword-based full-text retrieval using BM25 scoring. - Configurable number of results with `top_k`. - Supports fuzzy matching for handling typos and misspellings. - Supports metadata filtering to narrow down the search space. - Supports custom OpenSearch queries for advanced use cases. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `OpenSearchBM25Retriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `OpenSearchDocumentStore` with your OpenSearch instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `fuzziness`, `all_terms_must_match`, `scale_score`, `filter_policy`, and `custom_query`. ## Connections `OpenSearchBM25Retriever` receives the user query as a text string, typically from the `Input` component. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`bm25_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/bm25_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: filters: fuzziness: 0 top_k: 10 scale_score: false all_terms_must_match: false filter_policy: replace custom_query: raise_on_failure: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: filters: fuzziness: 0 top_k: 10 scale_score: false all_terms_must_match: false filter_policy: replace raise_on_failure: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true connections: [] max_runs_per_component: 100 metadata: {} inputs: query: - OpenSearchBM25Retriever.query outputs: documents: OpenSearchBM25Retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | | `fuzziness` | Optional[Union[int, str]] | Fuzziness for the BM25 query to allow for typos. | | `scale_score` | Optional[bool] | Whether to scale the document scores. | | `custom_query` | Optional[Dict[str, Any]] | A custom OpenSearch query to override the default BM25 query. | | `all_terms_must_match` | Optional[bool] | Whether all query terms must be present in the matching documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | OpenSearchDocumentStore | | An instance of `OpenSearchDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `fuzziness` | Union[int, str] | 0 | Fuzziness for matching. Use `"AUTO"` for automatic fuzziness based on term length. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `scale_score` | bool | False | Whether to scale scores to the range 0 to 1. | | `all_terms_must_match` | bool | False | If `True`, all query terms must appear in matching documents. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query structure. | | `raise_on_failure` | bool | True | Whether to raise an error when a query fails. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `all_terms_must_match` | Optional[bool] | None | Override the init-time setting. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | | `fuzziness` | Optional[Union[int, str]] | None | Override the init-time fuzziness setting. | | `scale_score` | Optional[bool] | None | Override the init-time scale_score setting. | | `custom_query` | Optional[Dict[str, Any]] | None | Override the init-time custom query. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## OpenSearchEmbeddingRetriever Retrieve documents from an `OpenSearchDocumentStore` using vector similarity search. ## Key Features - Dense vector-based retrieval from OpenSearch using k-NN similarity. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports custom OpenSearch queries for advanced use cases. - Configurable filter policy (`replace` or `merge`) for runtime filters. - Efficient filtering mode for improved performance with large datasets. ## Configuration 1. Drag the `OpenSearchEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `OpenSearchDocumentStore` with your OpenSearch instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`, `efficient_filtering`, and `custom_query`. ## Connections `OpenSearchEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: false document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace raise_on_failure: true efficient_filtering: false document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true connections: [] max_runs_per_component: 100 metadata: {} inputs: query_embedding: - OpenSearchEmbeddingRetriever.query_embedding outputs: documents: OpenSearchEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | | `custom_query` | Optional[Dict[str, Any]] | A custom OpenSearch query to use for retrieval. | | `efficient_filtering` | Optional[bool] | Whether to use efficient filtering mode. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | OpenSearchDocumentStore | | An instance of `OpenSearchDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query structure. | | `raise_on_failure` | bool | True | Whether to raise an error when a query fails. | | `efficient_filtering` | bool | False | When `True`, uses OpenSearch's post-filter for better performance with large indices. | | `search_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the OpenSearch k-NN search request. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | | `custom_query` | Optional[Dict[str, Any]] | None | Override the init-time custom query. | | `efficient_filtering` | Optional[bool] | None | Override the init-time efficient_filtering setting. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## OpenSearchHybridRetriever Retrieve documents from an `OpenSearchDocumentStore` using hybrid search, combining BM25 keyword-based retrieval with dense embedding retrieval. Use this super-component in query pipelines to get the benefits of both lexical and semantic search. ## Key Features - Combines BM25 keyword search and embedding-based vector search in a single component. - Uses Reciprocal Rank Fusion (RRF) by default to merge results, with configurable join modes and weights. - Exposes separate `top_k` and filter settings for each retrieval method. - Built as a Haystack `super_component` — wraps an internal pipeline with `OpenSearchBM25Retriever`, a text embedder, `OpenSearchEmbeddingRetriever`, and a `DocumentJoiner`. ## Configuration 1. First, configure an `OpenSearchDocumentStore` with both BM25 and embedding support. 2. Drag the `OpenSearchHybridRetriever` component onto the canvas from the Component Library. 3. Set the `embedder` parameter to a text embedder component (for example, `SentenceTransformersTextEmbedder`). 4. Adjust `top_k_bm25` and `top_k_embedding` to control how many candidates each retriever returns before merging. ## Connections `OpenSearchHybridRetriever` receives a text `query` string as input. It outputs a list of `Document` objects merged from both BM25 and embedding results. ## Source Code To check this component's source code, open [`open_search_hybrid_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/open_search_hybrid_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenSearchHybridRetriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: OpenSearchDocumentStore embedder: type: haystack_integrations.components.embedders.sentence_transformers.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 top_k_bm25: 10 top_k_embedding: 10 join_mode: reciprocal_rank_fusion ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters_bm25` | Optional[Dict[str, Any]] | Filters to apply to the BM25 retriever. | | `filters_embedding` | Optional[Dict[str, Any]] | Filters to apply to the embedding retriever. | | `top_k_bm25` | Optional[int] | Maximum number of BM25 results to return. Overrides the init-time value. | | `top_k_embedding` | Optional[int] | Maximum number of embedding results to return. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A merged list of documents from both BM25 and embedding retrieval. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | OpenSearchDocumentStore | | The OpenSearch document store to retrieve documents from. | | `embedder` | TextEmbedder | | A text embedder component used to embed the query for vector search. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Default filters to apply to BM25 retrieval. | | `fuzziness` | int or str | `0` | Fuzziness setting for BM25 keyword matching. | | `top_k_bm25` | int | `10` | Maximum number of BM25 candidates to retrieve. | | `scale_score` | bool | `False` | Whether to scale BM25 scores to a `[0, 1]` range. | | `all_terms_must_match` | bool | `False` | Whether all query terms must appear in a document for BM25 matching. | | `filter_policy_bm25` | FilterPolicy | `FilterPolicy.REPLACE` | Filter policy for BM25 retrieval. | | `custom_query_bm25` | Optional[Dict[str, Any]] | None | A custom OpenSearch query for BM25 retrieval. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Default filters to apply to embedding retrieval. | | `top_k_embedding` | int | `10` | Maximum number of embedding candidates to retrieve. | | `filter_policy_embedding` | FilterPolicy | `FilterPolicy.REPLACE` | Filter policy for embedding retrieval. | | `custom_query_embedding` | Optional[Dict[str, Any]] | None | A custom OpenSearch query for embedding retrieval. | | `join_mode` | JoinMode | `JoinMode.RECIPROCAL_RANK_FUSION` | How to merge results from BM25 and embedding retrievers. | | `weights` | Optional[List[float]] | None | Weights for each retriever when merging results. | | `top_k` | Optional[int] | None | Maximum number of documents to return after merging. | | `sort_by_score` | bool | `True` | Whether to sort merged results by score. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Runtime filters for BM25 retrieval. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Runtime filters for embedding retrieval. | | `top_k_bm25` | Optional[int] | None | Maximum BM25 results. Overrides the init-time value. | | `top_k_embedding` | Optional[int] | None | Maximum embedding results. Overrides the init-time value. | ## Related Information - [OpenSearchBM25Retriever](/docs/reference/pipeline-components/integrations/opensearch/OpenSearchBM25Retriever.mdx) - [OpenSearchEmbeddingRetriever](/docs/reference/pipeline-components/integrations/opensearch/OpenSearchEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## PerplexityChatGenerator Generate chat responses using Perplexity's language models via the Perplexity Agent API. ## Key Features - Uses Perplexity's Agent API, which is compatible with the OpenAI Responses API format. - Accepts and returns messages in `ChatMessage` format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports customizable generation parameters. ## Configuration 1. Drag the `PerplexityChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Perplexity model you want to use. 2. Create a secret with your Perplexity API key and set it as `api_key`. Use `PERPLEXITY_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, and `max_retries`. ## Connections `PerplexityChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/perplexity/src/haystack_integrations/components/generators/perplexity/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml PerplexityChatGenerator: type: haystack_integrations.components.generators.perplexity.chat.chat_generator.PerplexityChatGenerator init_parameters: api_key: type: env_var env_vars: - PERPLEXITY_API_KEY strict: false model: sonar generation_kwargs: max_tokens: 1024 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: "Answer the following question: {{ question }}" llm: type: haystack_integrations.components.generators.perplexity.chat.chat_generator.PerplexityChatGenerator init_parameters: api_key: type: env_var env_vars: - PERPLEXITY_API_KEY strict: false model: sonar generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("PERPLEXITY_API_KEY")` | The Perplexity API key. | | `model` | str | `openai/gpt-5.4` | The name of the Perplexity model to use. | | `api_base_url` | Optional[str] | `https://api.perplexity.ai/v1` | The base URL for the Perplexity API. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. | | `organization` | Optional[str] | None | The organization ID to use for requests. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters passed to the Perplexity API, such as `max_tokens`, `temperature`, and `top_p`. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## PerplexityWebSearch Search the web using the [Perplexity Search API](https://www.perplexity.ai/) and return results as Haystack Documents. ## Key Features - Web search powered by Perplexity's AI-enhanced search engine. - Returns search results as Haystack `Document` objects with content and metadata. - Also returns raw links alongside documents for downstream use. - Configurable number of results with `top_k`. - Supports additional Perplexity search parameters for customization. ## Configuration 1. Drag the `PerplexityWebSearch` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Perplexity API key and set it as `api_key`. Use `PERPLEXITY_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [perplexity.ai](https://www.perplexity.ai/). 2. Set `top_k` to control the maximum number of search results to return. 4. Go to the **Advanced** tab to configure `search_params` and `timeout`. ## Connections `PerplexityWebSearch` receives a query string and outputs a list of `Document` objects containing search result content and a list of raw URLs. Connect its `documents` output to a `PromptBuilder` or ranker to use the results in a pipeline. ## Source Code To check this component's source code, open [`perplexity_websearch.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/perplexity/src/haystack_integrations/components/websearch/perplexity/perplexity_websearch.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml PerplexityWebSearch: type: haystack_integrations.components.websearch.perplexity.perplexity_websearch.PerplexityWebSearch init_parameters: api_key: type: env_var env_vars: - PERPLEXITY_API_KEY strict: false top_k: 10 timeout: 30.0 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: PerplexityWebSearch: type: haystack_integrations.components.websearch.perplexity.perplexity_websearch.PerplexityWebSearch init_parameters: api_key: type: env_var env_vars: - PERPLEXITY_API_KEY strict: false top_k: 5 prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: | Answer based on these web search results: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini connections: - sender: PerplexityWebSearch.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: llm.messages max_runs_per_component: 100 metadata: {} inputs: query: - PerplexityWebSearch.query - prompt_builder.question ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The search query to send to Perplexity. | | `search_params` | Optional[Dict[str, Any]] | Additional Perplexity search parameters to override init-time values. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The search results as Haystack Documents. | | `links` | List[str] | The URLs of the search results. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("PERPLEXITY_API_KEY")` | The Perplexity API key. | | `top_k` | Optional[int] | 10 | The maximum number of search results to return. | | `search_params` | Optional[Dict[str, Any]] | None | Additional Perplexity API parameters. | | `timeout` | float | 30.0 | Request timeout in seconds. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The search query to send to Perplexity. | | `search_params` | Optional[Dict[str, Any]] | None | Additional search parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## PgvectorEmbeddingRetriever Retrieve documents from a `PgvectorDocumentStore` using dense vector embeddings. ## Key Features - Dense vector-based retrieval from PostgreSQL with the [pgvector](https://github.com/pgvector/pgvector) extension. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports multiple vector similarity functions: cosine similarity, inner product, and L2 distance. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `PgvectorEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `PgvectorDocumentStore` with your PostgreSQL connection string. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `vector_function` and `filter_policy`. ## Connections `PgvectorEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pgvector/src/haystack_integrations/components/retrievers/pgvector/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml PgvectorEmbeddingRetriever: type: haystack_integrations.components.retrievers.pgvector.embedding_retriever.PgvectorEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.pgvector.document_store.PgvectorDocumentStore init_parameters: connection_string: type: env_var env_vars: - PG_CONN_STR strict: false table_name: haystack_documents embedding_dimension: 768 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: PgvectorEmbeddingRetriever: type: haystack_integrations.components.retrievers.pgvector.embedding_retriever.PgvectorEmbeddingRetriever init_parameters: top_k: 10 filter_policy: replace document_store: type: haystack_integrations.document_stores.pgvector.document_store.PgvectorDocumentStore init_parameters: connection_string: type: env_var env_vars: - PG_CONN_STR strict: false table_name: haystack_documents embedding_dimension: 768 vector_function: cosine_similarity connections: [] max_runs_per_component: 100 metadata: {} inputs: query_embedding: - PgvectorEmbeddingRetriever.query_embedding outputs: documents: PgvectorEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | | `vector_function` | Optional[Literal] | The vector similarity function to use. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | PgvectorDocumentStore | | An instance of `PgvectorDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `vector_function` | Optional[Literal["cosine_similarity", "inner_product", "l2_distance"]] | None | The vector similarity function to use. If not set, uses the function configured in the document store. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query_embedding` | List[float] | | The embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | | `vector_function` | Optional[Literal] | None | Override the init-time vector function. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## PgvectorKeywordRetriever Retrieve documents from a `PgvectorDocumentStore` using keyword-based full-text search. ## Key Features - Full-text search using PostgreSQL's `ts_rank_cd` ranking function. - Ranks documents based on query term frequency, proximity, and position. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `PgvectorKeywordRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `PgvectorDocumentStore` with your PostgreSQL connection string. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`. ## Connections `PgvectorKeywordRetriever` receives the user query as a text string, typically from the `Input` component. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`keyword_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pgvector/src/haystack_integrations/components/retrievers/pgvector/keyword_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml PgvectorKeywordRetriever: type: haystack_integrations.components.retrievers.pgvector.keyword_retriever.PgvectorKeywordRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.pgvector.document_store.PgvectorDocumentStore init_parameters: connection_string: type: env_var env_vars: - PG_CONN_STR strict: false table_name: haystack_documents language: english ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: PgvectorKeywordRetriever: type: haystack_integrations.components.retrievers.pgvector.keyword_retriever.PgvectorKeywordRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.pgvector.document_store.PgvectorDocumentStore init_parameters: connection_string: type: env_var env_vars: - PG_CONN_STR strict: false table_name: haystack_documents connections: [] max_runs_per_component: 100 metadata: {} inputs: query: - PgvectorKeywordRetriever.query outputs: documents: PgvectorKeywordRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | Filters to apply to the search results. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | PgvectorDocumentStore | | An instance of `PgvectorDocumentStore`. | | `filters` | Optional[Dict[str, Any]] | None | Default filters applied when running the retriever. | | `top_k` | int | 10 | The maximum number of documents to retrieve. | | `filter_policy` | Union[str, FilterPolicy] | `FilterPolicy.REPLACE` | Policy for how runtime filters are applied relative to init-time filters. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query to search for. | | `filters` | Optional[Dict[str, Any]] | None | Filters to apply at query time. | | `top_k` | Optional[int] | None | Override the init-time `top_k` setting. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## PineconeEmbeddingRetriever Retrieve documents from the `PineconeDocumentStore` based on their dense embeddings. It compares the query and document embeddings and fetches the documents most relevant to the query based on vector similarity. [Pinecone](https://www.pinecone.io/) is a managed vector database service that enables fast and scalable similarity search. It's designed for production workloads with features like automatic scaling, high availability, and real-time updates. ## Key Features - Embedding-based retrieval from a Pinecone vector database. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Configurable filter policy (`replace` or `merge`) for runtime filters. - Works with any text embedder that produces dense vector embeddings. ## Configuration 1. Drag the `PineconeEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `PineconeDocumentStore` with your Pinecone index, namespace, and embedding dimensions. Make sure you have a secret called `PINECONE_API_KEY` in your workspace. For instructions, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy` and default filters. ## Connections `PineconeEmbeddingRetriever` receives the query embedding from a text embedder like `SentenceTransformersTextEmbedder` or `OpenAITextEmbedder`. It sends retrieved documents to `PromptBuilder` for use in a prompt, or to a `Ranker` to reorder them by relevance. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/pinecone/src/haystack_integrations/components/retrievers/pinecone/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml PineconeEmbeddingRetriever: type: haystack_integrations.components.retrievers.pinecone.embedding_retriever.PineconeEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.pinecone.document_store.PineconeDocumentStore init_parameters: api_key: type: env_var env_vars: - PINECONE_API_KEY strict: true index: my-index namespace: my-namespace dimension: 384 metric: cosine top_k: 10 filter_policy: replace ``` This is an example of a semantic search pipeline where `PineconeEmbeddingRetriever` receives the query embedding from a text embedder and retrieves matching documents. ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false PineconeEmbeddingRetriever: type: haystack_integrations.components.retrievers.pinecone.embedding_retriever.PineconeEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.pinecone.document_store.PineconeDocumentStore init_parameters: api_key: type: env_var env_vars: - PINECONE_API_KEY strict: true index: my-index namespace: my-namespace dimension: 384 metric: cosine spec: filters: top_k: 10 filter_policy: replace connections: - sender: text_embedder.embedding receiver: PineconeEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - text_embedder.text filters: - PineconeEmbeddingRetriever.filters outputs: documents: PineconeEmbeddingRetriever.documents ``` This example shows a RAG pipeline that uses `PineconeEmbeddingRetriever` to find relevant documents, then passes them to a generator to answer a question. ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false retriever: type: haystack_integrations.components.retrievers.pinecone.embedding_retriever.PineconeEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.pinecone.document_store.PineconeDocumentStore init_parameters: api_key: type: env_var env_vars: - PINECONE_API_KEY strict: true index: my-index namespace: my-namespace dimension: 384 metric: cosine spec: filters: top_k: 10 filter_policy: replace prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- Given the following documents, answer the question. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} Answer: generator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o-mini generation_kwargs: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: text_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt max_runs_per_component: 100 metadata: {} inputs: query: - text_embedder.text - prompt_builder.question - answer_builder.query filters: - retriever.filters outputs: documents: retriever.documents answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | Embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. | | `top_k` | Optional[int] | Maximum number of `Document`s to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents similar to the query embedding. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|------------------------|--------------------|--------------------------------------------| |document_store|PineconeDocumentStore | |The Pinecone Document Store. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved Documents. | |top_k |int | 10|Maximum number of Documents to return. | |filter_policy |Union[str, FilterPolicy]|FilterPolicy.REPLACE|Policy to determine how filters are applied.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding|List[float] | |Embedding of the query. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. See init method docstring for more details.| |top_k |Optional[int] |None |Maximum number of `Document`s to return. | ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## QdrantEmbeddingRetriever Retrieve documents from a `QdrantDocumentStore` using dense vector embeddings. ## Key Features - Dense vector-based retrieval from a Qdrant vector database. - Configurable number of results with `top_k` and minimum score threshold. - Supports metadata filtering to narrow down the search space. - Supports document grouping by a payload field. - Optional score scaling and embedding return. ## Configuration 1. Drag the `QdrantEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `QdrantDocumentStore` with your Qdrant instance details. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`, `score_threshold`, `scale_score`, `group_by`, and `group_size`. ## Connections `QdrantEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/qdrant/src/haystack_integrations/components/retrievers/qdrant/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml QdrantEmbeddingRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantEmbeddingRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: QdrantEmbeddingRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantEmbeddingRetriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | Embedding of the query. | | `filters` | Optional[Union[Dict[str, Any], models.Filter]] | A dictionary with filters to narrow down the search space. | | `top_k` | Optional[int] | The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | | `scale_score` | Optional[bool] | Whether to scale the scores of the retrieved documents or not. | | `return_embedding` | Optional[bool] | Whether to return the embedding of the retrieved Documents. | | `score_threshold` | Optional[float] | A minimal score threshold for the result. | | `group_by` | Optional[str] | Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | | `group_size` | Optional[int] | Maximum amount of points to return per group. Default is 3. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------|----------------------------------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store |QdrantDocumentStore | |An instance of QdrantDocumentStore. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |A dictionary with filters to narrow down the search space. | |top_k |int | 10|The maximum number of documents to retrieve. If using `group_by` parameters, maximum number of groups to return. | |scale_score |bool |False |Whether to scale the scores of the retrieved documents or not. | |return_embedding|bool |False |Whether to return the embedding of the retrieved Documents. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied. | |score_threshold |Optional[float] |None |A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the `similarity` function specified in the Document Store. For example, for cosine similarity only higher scores will be returned.| |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |----------------|----------------------------------------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding |List[float] | |Embedding of the query. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |A dictionary with filters to narrow down the search space. | |top_k |Optional[int] |None |The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | |scale_score |Optional[bool] |None |Whether to scale the scores of the retrieved documents or not. | |return_embedding|Optional[bool] |None |Whether to return the embedding of the retrieved Documents. | |score_threshold |Optional[float] |None |A minimal score threshold for the result. | |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups.| |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | --- ## QdrantHybridRetriever Retrieve documents from a `QdrantDocumentStore` using both dense and sparse vectors, fusing the results using Reciprocal Rank Fusion. ## Key Features - Hybrid retrieval combining dense and sparse vector search from Qdrant. - Uses Reciprocal Rank Fusion to combine results from both retrieval methods. - Configurable number of results with `top_k` and minimum score threshold. - Supports metadata filtering to narrow down the search space. - Supports document grouping by a payload field. ## Configuration 1. Drag the `QdrantHybridRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `QdrantDocumentStore` with your Qdrant instance details. Make sure your Qdrant index uses sparse embeddings (`use_sparse_embeddings=True`). - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`, `score_threshold`, `return_embedding`, `group_by`, and `group_size`. ## Connections `QdrantHybridRetriever` receives both a dense query embedding and a sparse query embedding as inputs. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/qdrant/src/haystack_integrations/components/retrievers/qdrant/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml QdrantHybridRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantHybridRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: QdrantHybridRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantHybridRetriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | Dense embedding of the query. | | `query_sparse_embedding` | SparseEmbedding | Sparse embedding of the query. | | `filters` | Optional[Union[Dict[str, Any], models.Filter]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. | | `top_k` | Optional[int] | The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | | `return_embedding` | Optional[bool] | Whether to return the embedding of the retrieved Documents. | | `score_threshold` | Optional[float] | A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. | | `group_by` | Optional[str] | Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | | `group_size` | Optional[int] | Maximum amount of points to return per group. Default is 3. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------|----------------------------------------------|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store |QdrantDocumentStore | |An instance of QdrantDocumentStore. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |A dictionary with filters to narrow down the search space. | |top_k |int | 10|The maximum number of documents to retrieve. If using `group_by` parameters, maximum number of groups to return. | |return_embedding|bool |False |Whether to return the embeddings of the retrieved Documents. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied. | |score_threshold |Optional[float] |None |A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. For example, for cosine similarity only higher scores will be returned.| |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |----------------------|----------------------------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding |List[float] | |Dense embedding of the query. | |query_sparse_embedding|SparseEmbedding | |Sparse embedding of the query. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. See init method docstring for more details. | |top_k |Optional[int] |None |The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | |return_embedding |Optional[bool] |None |Whether to return the embedding of the retrieved Documents. | |score_threshold |Optional[float] |None |A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. For example, for cosine similarity only higher scores will be returned.| |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | --- ## QdrantSparseEmbeddingRetriever Retrieve documents from a `QdrantDocumentStore` using sparse vector embeddings. ## Key Features - Sparse vector-based retrieval from a Qdrant vector database. - Configurable number of results with `top_k` and minimum score threshold. - Supports metadata filtering to narrow down the search space. - Supports document grouping by a payload field. - Optional score scaling and sparse embedding return. ## Configuration 1. Drag the `QdrantSparseEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `QdrantDocumentStore` with your Qdrant instance details. Make sure your Qdrant index uses sparse embeddings (`use_sparse_embeddings=True`). - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`, `score_threshold`, `scale_score`, `return_embedding`, `group_by`, and `group_size`. ## Connections `QdrantSparseEmbeddingRetriever` receives sparse query embeddings from a sparse text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/qdrant/src/haystack_integrations/components/retrievers/qdrant/retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml QdrantSparseEmbeddingRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantSparseEmbeddingRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: QdrantSparseEmbeddingRetriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantSparseEmbeddingRetriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_sparse_embedding` | SparseEmbedding | Sparse Embedding of the query. | | `filters` | Optional[Union[Dict[str, Any], models.Filter]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. | | `top_k` | Optional[int] | The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | | `scale_score` | Optional[bool] | Whether to scale the scores of the retrieved documents or not. | | `return_embedding` | Optional[bool] | Whether to return the embedding of the retrieved Documents. | | `score_threshold` | Optional[float] | A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. | | `group_by` | Optional[str] | Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | | `group_size` | Optional[int] | Maximum amount of points to return per group. Default is 3. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------|----------------------------------------------|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |document_store |QdrantDocumentStore | |An instance of QdrantDocumentStore. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |A dictionary with filters to narrow down the search space. | |top_k |int | 10|The maximum number of documents to retrieve. If using `group_by` parameters, maximum number of groups to return. | |scale_score |bool |False |Whether to scale the scores of the retrieved documents or not. | |return_embedding|bool |False |Whether to return the sparse embedding of the retrieved Documents. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE|Policy to determine how filters are applied. Defaults to "replace". | |score_threshold |Optional[float] |None |A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. For example, for cosine similarity only higher scores will be returned.| |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |----------------------|----------------------------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_sparse_embedding|SparseEmbedding | |Sparse Embedding of the query. | |filters |Optional[Union[Dict[str, Any], models.Filter]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. See init method docstring for more details. | |top_k |Optional[int] |None |The maximum number of documents to return. If using `group_by` parameters, maximum number of groups to return. | |scale_score |Optional[bool] |None |Whether to scale the scores of the retrieved documents or not. | |return_embedding |Optional[bool] |None |Whether to return the embedding of the retrieved Documents. | |score_threshold |Optional[float] |None |A minimal score threshold for the result. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. For example, for cosine similarity only higher scores will be returned.| |group_by |Optional[str] |None |Payload field to group by, must be a string or number field. If the field contains more than one value, all values will be used for grouping. One point can be in multiple groups. | |group_size |Optional[int] |None |Maximum amount of points to return per group. Default is 3. | --- ## SearchApiWebSearch Search the web for relevant documents using [SearchApi](https://www.searchapi.io/). Use this component in pipelines that need to retrieve information from the web. ## Key Features - Searches the web using the SearchApi service. - Configurable number of results with `top_k`. - Supports filtering results by allowed domains. - Supports passing additional parameters to the SearchApi API, including the ability to change the search engine. - Returns both documents and links from the search results. ## Configuration 1. Drag the `SearchApiWebSearch` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `SEARCHAPI_API_KEY` secret in your workspace. For instructions, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Set `top_k` to control the number of results to return. 4. Go to the **Advanced** tab to configure `allowed_domains` and `search_params`. ## Connections `SearchApiWebSearch` receives a search query string as input. It outputs a list of documents and a list of links. Connect it to components that process or present web search results. ## Source Code To check this component's source code, open [`searchapi.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/websearch/searchapi.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml SearchApiWebSearch: type: haystack.components.websearch.searchapi.SearchApiWebSearch init_parameters: {} ``` Connect the pipeline's query input to its `query` input. Connect its `documents` output to a `PromptBuilder` or other components that process retrieved content. ```yaml # haystack-pipeline components: SearchApiWebSearch: type: haystack.components.websearch.searchapi.SearchApiWebSearch init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | Search query. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents returned by the search engine. | | `links` | List[str] | List of links returned by the search engine. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------|------------------------|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('SEARCHAPI_API_KEY')|API key for the SearchApi API | |top_k |Optional[int] |10 |Number of documents to return. | |allowed_domains|Optional[List[str]] |None |List of domains to limit the search to. | |search_params |Optional[Dict[str, Any]]|None |Additional parameters passed to the SearchApi API. For example, you can set 'num' to 100 to increase the number of search results. See the [SearchApi website](https://www.searchapi.io/) for more details. The default search engine is Google, however, users can change it by setting the `engine` parameter in the `search_params`.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|-------------| |query |str | |Search query.| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## SentenceTransformersDocumentEmbedder Compute embeddings for a list of documents using [Sentence Transformers](https://www.sbert.net/) models. Use this component in indexing pipelines to prepare documents for embedding-based retrieval. ## Key Features - Works with any model available on Hugging Face that is compatible with Sentence Transformers. - Stores the computed embedding in each document's `embedding` field. - Supports embedding metadata fields alongside document content. - Supports multiple embedding precisions including float32, int8, uint8, binary, and ubinary. - Supports model quantization and custom backends (PyTorch, ONNX, OpenVINO). ## Configuration 1. Drag the `SentenceTransformersDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Sentence Transformers model you want to use (for example, `sentence-transformers/all-mpnet-base-v2`). 2. Optionally set a Hugging Face token if using private or gated models. 4. Go to the **Advanced** tab to configure `meta_fields_to_embed`, `embedding_separator`, `normalize_embeddings`, `batch_size`, and `precision`. ## Connections `SentenceTransformersDocumentEmbedder` receives a list of documents, typically from a document splitter or converter. It outputs the same documents with embeddings added to their `embedding` field, ready to be sent to a `DocumentWriter`. ## Source Code To check this component's source code, open [`sentence_transformers_document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/sentence_transformers/src/haystack_integrations/components/embedders/sentence_transformers/sentence_transformers_document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml SentenceTransformersDocumentEmbedder: type: haystack_integrations.components.embedders.sentence_transformers.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 batch_size: 32 normalize_embeddings: false ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: SentenceTransformersDocumentEmbedder: type: haystack_integrations.components.embedders.sentence_transformers.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 batch_size: 32 normalize_embeddings: false token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false meta_fields_to_embed: embedding_separator: "\n" document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 connections: - sender: SentenceTransformersDocumentEmbedder.documents receiver: document_writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents with their `embedding` field populated. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `sentence-transformers/all-mpnet-base-v2` | The name of the Sentence Transformers model from Hugging Face. | | `device` | Optional[ComponentDevice] | None | The device to run the model on. If not set, automatically detected. | | `token` | Optional[Secret] | `Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"])` | A Hugging Face token for accessing private or gated models. | | `prefix` | str | `""` | A string to add at the beginning of each document's text before embedding. | | `suffix` | str | `""` | A string to add at the end of each document's text before embedding. | | `batch_size` | int | 32 | The number of documents to process in each batch. | | `progress_bar` | bool | True | Whether to show a progress bar during embedding. | | `normalize_embeddings` | bool | False | Whether to normalize embedding vectors to unit length. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text before embedding. | | `embedding_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | | `trust_remote_code` | bool | False | Whether to trust remote code when loading models with custom code. | | `local_files_only` | bool | False | Whether to use only local files, without downloading from Hugging Face. | | `truncate_dim` | Optional[int] | None | The dimension to truncate the embedding to. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments passed to the model constructor. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the model configuration. | | `precision` | Literal["float32", "int8", "uint8", "binary", "ubinary"] | `"float32"` | The precision of the output embeddings. | | `encode_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the `encode()` method. | | `backend` | Literal["torch", "onnx", "openvino"] | `"torch"` | The backend to use for inference. | | `revision` | Optional[str] | None | The model revision to use. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## SentenceTransformersTextEmbedder Embed strings using [Sentence Transformers](https://www.sbert.net/) models. Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Works with any model available on Hugging Face that is compatible with Sentence Transformers. - Outputs a float vector embedding suitable for use with embedding retrievers. - Supports multiple embedding precisions including float32, int8, uint8, binary, and ubinary. - Supports model quantization and custom backends (PyTorch, ONNX, OpenVINO). - The embedding model must match the one used by `SentenceTransformersDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `SentenceTransformersTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Sentence Transformers model you want to use (for example, `sentence-transformers/all-mpnet-base-v2`). 2. Optionally set a Hugging Face token if using private or gated models. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `normalize_embeddings`, `truncate_dim`, `precision`, and `backend`. ## Connections `SentenceTransformersTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever such as `OpenSearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`sentence_transformers_text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/sentence_transformers/src/haystack_integrations/components/embedders/sentence_transformers/sentence_transformers_text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml SentenceTransformersTextEmbedder: type: haystack_integrations.components.embedders.sentence_transformers.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 normalize_embeddings: false progress_bar: true ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: SentenceTransformersTextEmbedder: type: haystack_integrations.components.embedders.sentence_transformers.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 normalize_embeddings: false token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 768 connections: - sender: SentenceTransformersTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - SentenceTransformersTextEmbedder.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `sentence-transformers/all-mpnet-base-v2` | The name of the Sentence Transformers model from Hugging Face. | | `device` | Optional[ComponentDevice] | None | The device to run the model on. If not set, automatically detected. | | `token` | Optional[Secret] | `Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"])` | A Hugging Face token for accessing private or gated models. | | `prefix` | str | `""` | A string to add at the beginning of the text before embedding. | | `suffix` | str | `""` | A string to add at the end of the text before embedding. | | `batch_size` | int | 32 | The number of texts to process in each batch. | | `progress_bar` | bool | True | Whether to show a progress bar during embedding. | | `normalize_embeddings` | bool | False | Whether to normalize embedding vectors to unit length. | | `trust_remote_code` | bool | False | Whether to trust remote code when loading models with custom code. | | `local_files_only` | bool | False | Whether to use only local files, without downloading from Hugging Face. | | `truncate_dim` | Optional[int] | None | The dimension to truncate the embedding to. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments passed to the model constructor. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the model configuration. | | `precision` | Literal["float32", "int8", "uint8", "binary", "ubinary"] | `"float32"` | The precision of the output embeddings. | | `encode_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the `encode()` method. | | `backend` | Literal["torch", "onnx", "openvino"] | `"torch"` | The backend to use for inference. | | `revision` | Optional[str] | None | The model revision to use. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## SerperDevWebSearch Search the web for relevant documents using [Serper](https://serper.dev/). Use this component in pipelines that need to retrieve information from the web. ## Key Features - Searches the web using the Serper Dev API. - Configurable number of results with `top_k`. - Supports filtering results by allowed domains. - Supports passing additional parameters to the Serper API for advanced query control. - Returns both documents and links from the search results. ## Configuration 1. Drag the `SerperDevWebSearch` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `SERPERDEV_API_KEY` secret in your workspace. For instructions, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Set `top_k` to control the number of results to return. 4. Go to the **Advanced** tab to configure `allowed_domains` and `search_params`. ## Connections `SerperDevWebSearch` receives a search query string as input. It outputs a list of documents and a list of links. Connect it to components that process or present web search results. ## Source Code To check this component's source code, open [`serper_dev.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/websearch/serper_dev.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml # haystack-pipeline components: SerperDevWebSearch: type: haystack.components.websearch.serper_dev.SerperDevWebSearch init_parameters: ``` Connect the pipeline's query input to its `query` input. Connect its `documents` output to a `PromptBuilder` or other components that process retrieved content. ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | Search query. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | List of documents returned by the search engine. | | `links` | List[str] | List of links returned by the search engine. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------|------------------------|----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('SERPERDEV_API_KEY')|API key for the Serper API. | |top_k |Optional[int] |10 |Number of documents to return. | |allowed_domains|Optional[List[str]] |None |List of domains to limit the search to. | |search_params |Optional[Dict[str, Any]]|None |Additional parameters passed to the Serper API. For example, you can set 'num' to 20 to increase the number of search results. See the [Serper website](https://serper.dev/) for more details.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|-------------| |query |str | |Search query.| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## SnowflakeTableRetriever Connect to a Snowflake database and execute SQL queries using ADBC and Polars. It returns the results as a Pandas DataFrame and optionally as a Markdown-formatted string. For more information, see [Polars documentation](https://docs.pola.rs/api/python/dev/reference/api/polars.read_database_uri.html) and [ADBC documentation](https://arrow.apache.org/adbc/main/driver/snowflake.html). ## Key Features - Executes SQL queries against a Snowflake database using ADBC and Polars. - Returns query results as a Pandas DataFrame and as a Markdown-formatted table. - Configurable login timeout. - Supports passing the SQL query at runtime for dynamic data retrieval. ## Configuration 1. Drag the `SnowflakeTableRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set your Snowflake `user`, `account`, and `api_key` (password). Store the password as a secret called `SNOWFLAKE_API_KEY`. For instructions, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Set the `database`, `db_schema`, and `warehouse` for your Snowflake connection. 4. Go to the **Advanced** tab to configure `login_timeout` and `return_markdown`. ## Connections `SnowflakeTableRetriever` receives SQL queries at runtime. It outputs the query results as a `dataframe` (Pandas DataFrame) and optionally as a `table` (Markdown string). Connect it to components that process or format the query results. ## Source Code To check this component's source code, open [`snowflake_table_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/snowflake/src/haystack_integrations/components/retrievers/snowflake/snowflake_table_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml SnowflakeTableRetriever: type: snowflake.src.haystack_integrations.components.retrievers.snowflake.snowflake_table_retriever.SnowflakeTableRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: SnowflakeTableRetriever: type: haystack_integrations.components.retrievers.snowflake.snowflake_table_retriever.SnowflakeTableRetriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The SQL query to execute. | | `return_markdown` | Optional[bool] | Whether to return a Markdown-formatted string of the DataFrame. If not provided, uses the value set during initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `dataframe` | DataFrame | A Pandas DataFrame with the query results. | | `table` | str | A Markdown-formatted string representation of the DataFrame. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------|-------------|----------------------------------------|---------------------------------------------------------------| |user |str | |User's login. | |account |str | |Snowflake account identifier. | |api_key |Secret |Secret.from_env_var('SNOWFLAKE_API_KEY')|Snowflake account password. | |database |Optional[str]|None |Name of the database to use. | |db_schema |Optional[str]|None |Name of the schema to use. | |warehouse |Optional[str]|None |Name of the warehouse to use. | |login_timeout |Optional[int]|60 |Timeout in seconds for login. | |return_markdown|bool |True |Whether to return a Markdown-formatted string of the DataFrame.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|--------------|-------|--------------------------------------------------------------------------------------------------------------------------| |query |str | |The SQL query to execute. | |return_markdown|Optional[bool]|None |Whether to return a Markdown-formatted string of the DataFrame. If not provided, uses the value set during initialization.| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## STACKITChatGenerator Generate text using STACKIT generative models through their model serving service. For a list of supported models, see [STACKIT documentation](https://docs.stackit.cloud/docs/stackit-ai/generative-models). ## Key Features - Supports all models available through STACKIT's model serving API. - Accepts all parameters supported by the STACKIT chat completion endpoint via `generation_kwargs`. - Supports tool calling with Haystack tools and Toolsets. - Supports streaming responses token by token. ## Configuration 1. Drag the `STACKITChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your STACKIT account by creating a secret called `STACKIT_API_KEY`. For more information about secrets, see [Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Select the model to use. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, `max_retries`, and `http_client_kwargs`. ## Connections `STACKITChatGenerator` receives rendered chat prompts from `ChatPromptBuilder` through its `messages` input. It sends generated replies through its `replies` output to downstream components such as `OutputAdapter` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/stackit/src/haystack_integrations/components/generators/stackit/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml STACKITChatGenerator: type: haystack_integrations.components.generators.stackit.chat.chat_generator.STACKITChatGenerator init_parameters: api_key: type: env_var env_vars: - STACKIT_API_KEY strict: false api_base_url: https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1 ``` This is an example RAG pipeline with `STACKITChatGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false STACKITChatGenerator: type: haystack_integrations.components.generators.stackit.chat.chat_generator.STACKITChatGenerator init_parameters: model: api_key: type: env_var env_vars: - STACKIT_API_KEY strict: false api_base_url: https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1 generation_kwargs: streaming_callback: timeout: max_retries: http_client_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: STACKITChatGenerator.messages - sender: STACKITChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For a list of supported parameters, see [STACKIT documentation](https://docs.stackit.cloud/docs/stackit-ai/generative-models). | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter in pipeline configuration. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | | `tools_strict` | Optional[bool] | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|----------------------------|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |str | |The name of the chat completion model to use. | |api_key |Secret |Secret.from_env_var('STACKIT_API_KEY') |The STACKIT API key. | |streaming_callback|Optional[StreamingCallbackT]|None |A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | |api_base_url |Optional[str] |https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1|The STACKIT API Base url. | |generation_kwargs |Optional[Dict[str, Any]] |None |Other parameters to use for the model. These parameters are all sent directly to the STACKIT endpoint. Some of the supported parameters: - `max_tokens`: The maximum number of tokens the output text can have. - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. - `safe_prompt`: Whether to inject a safety prompt before all conversations. - `random_seed`: The seed to use for random sampling.| |timeout |Optional[float] |None |Timeout for STACKIT client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact STACKIT after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]] |None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |------------------|------------------------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |messages |List[ChatMessage] | |A list of ChatMessage instances representing the input messages. | |streaming_callback|Optional[StreamingCallbackT] |None |A callback function that is called when a new token is received from the stream. | |generation_kwargs |Optional[Dict[str, Any]] |None |Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For a list of supported parameters, see [STACKIT documentation](https://docs.stackit.cloud/docs/stackit-ai/generative-models). | |tools |Optional[Union[List[Tool], Toolset]]|None |A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter in pipeline configuration. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | |tools_strict |Optional[bool] |None |Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. If set, it overrides the `tools_strict` parameter in pipeline configuration.| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## STACKITDocumentEmbedder Compute document embeddings using STACKIT as the model provider. The embedding of each document is stored in the `embedding` field of the Document object. ## Key Features - Computes dense vector embeddings for documents using STACKIT embedding models. - Embeds documents in configurable batch sizes for efficient processing. - Optionally embeds metadata fields along with document content. - Configurable prefix and suffix for text preprocessing. ## Configuration 1. Drag the `STACKITDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your STACKIT account by creating a secret called `STACKIT_API_KEY`. For more information about secrets, see [Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Select the embedding model to use. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `http_client_kwargs`, `prefix`, `suffix`, and metadata embedding options. ## Connections `STACKITDocumentEmbedder` receives documents to embed from PreProcessors like `DocumentSplitter`. It sends the embedded documents to `DocumentWriter`, which writes them into a document store. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/stackit/src/haystack_integrations/components/embedders/stackit/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml STACKITDocumentEmbedder: type: haystack_integrations.components.embedders.stackit.document_embedder.STACKITDocumentEmbedder init_parameters: {} ``` Use this component in indexing pipelines. Connect a preprocessor like `DocumentSplitter` to its `documents` input, and connect its `documents` output to `DocumentWriter`. ```yaml # haystack-pipeline components: STACKITDocumentEmbedder: type: haystack_integrations.components.embedders.stackit.document_embedder.STACKITDocumentEmbedder init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents with embeddings stored in the `embedding` field. | | `meta` | Dict[str, Any] | Information about the embedding operation. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|------------------------|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('STACKIT_API_KEY') |The STACKIT API key. | |model |str | |The name of the model to use. | |api_base_url |Optional[str] |https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1|The STACKIT API Base url. For more details, see STACKIT [docs](https://docs.stackit.cloud/stackit/en/basic-concepts-stackit-model-serving-319914567.html). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |batch_size |int | 32|Number of Documents to encode at once. | |progress_bar |bool |True |Whether to show a progress bar or not. Can be helpful to disable in production deployments to keep the logs clean. | |meta_fields_to_embed|Optional[List[str]] |None |List of meta fields that should be embedded along with the Document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the Document text. | |timeout |Optional[float] |None |Timeout for STACKIT client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact STACKIT after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs |Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). This component has no run() method parameters. ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## STACKITTextEmbedder Embed strings using STACKIT as the model provider. Use this component in query pipelines when you want to perform semantic search. ## Key Features - Embeds text strings (queries) using STACKIT embedding models. - Outputs the embedding for use with embedding-based retrievers. - Configurable prefix and suffix for text preprocessing. ## Configuration 1. Drag the `STACKITTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your STACKIT account by creating a secret called `STACKIT_API_KEY`. For more information about secrets, see [Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). - Select the embedding model to use. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `http_client_kwargs`, `prefix`, and `suffix`. ## Connections `STACKITTextEmbedder` receives text to embed from the `Input` component. It sends the embedding to embedding-based retrievers. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/stackit/src/haystack_integrations/components/embedders/stackit/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml STACKITTextEmbedder: type: haystack_integrations.components.embedders.stackit.text_embedder.STACKITTextEmbedder init_parameters: {} ``` Use this component in query pipelines for semantic search. Connect its `embedding` output to an embedding retriever. ```yaml # haystack-pipeline components: STACKITTextEmbedder: type: haystack_integrations.components.embedders.stackit.text_embedder.STACKITTextEmbedder init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the input text. | | `meta` | Dict[str, Any] | Information about the embedding operation. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|------------------------|---------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_key |Secret |Secret.from_env_var('STACKIT_API_KEY') |The STACKIT API key. | |model |str | |The name of the STACKIT embedding model to be used. | |api_base_url |Optional[str] |https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1|The STACKIT API Base url. For more details, see STACKIT [docs](https://docs.stackit.cloud/stackit/en/basic-concepts-stackit-model-serving-319914567.html). | |prefix |str | |A string to add to the beginning of each text. | |suffix |str | |A string to add to the end of each text. | |timeout |Optional[float] |None |Timeout for STACKIT client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable, or 30 seconds. | |max_retries |Optional[int] |None |Maximum number of retries to contact STACKIT after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5. | |http_client_kwargs|Optional[Dict[str, Any]]|None |A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). This component has no run() method parameters. ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## TavilyWebSearch Search the web using [Tavily](https://tavily.com), an AI-powered search API optimized for LLM applications. ## Key Features - AI-powered web search optimized for use in LLM pipelines. - Returns search results as Haystack `Document` objects with content and metadata. - Also returns raw links alongside documents for downstream use. - Configurable number of results with `top_k`. - Supports additional Tavily search parameters like `search_depth`, `include_domains`, and `exclude_domains`. ## Configuration 1. Drag the `TavilyWebSearch` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your Tavily API key and set it as `api_key`. Use `TAVILY_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). Get your API key from [tavily.com](https://tavily.com). 2. Set `top_k` to control the maximum number of search results to return. 4. Go to the **Advanced** tab to configure `search_params` for Tavily-specific options such as `search_depth`, `include_domains`, and `exclude_domains`. ## Connections `TavilyWebSearch` receives a query string and outputs a list of `Document` objects containing search result content and a list of raw URLs. Connect its `documents` output to a `PromptBuilder` or ranker to use the results in a pipeline. ## Source Code To check this component's source code, open [`tavily_websearch.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/tavily/src/haystack_integrations/components/websearch/tavily/tavily_websearch.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml TavilyWebSearch: type: haystack_integrations.components.websearch.tavily.tavily_websearch.TavilyWebSearch init_parameters: api_key: type: env_var env_vars: - TAVILY_API_KEY strict: false top_k: 10 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: TavilyWebSearch: type: haystack_integrations.components.websearch.tavily.tavily_websearch.TavilyWebSearch init_parameters: api_key: type: env_var env_vars: - TAVILY_API_KEY strict: false top_k: 5 search_params: search_depth: advanced prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: | Answer based on these web search results: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini connections: - sender: TavilyWebSearch.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: llm.messages max_runs_per_component: 100 metadata: {} inputs: query: - TavilyWebSearch.query - prompt_builder.question ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The search query to send to Tavily. | | `search_params` | Optional[Dict[str, Any]] | Additional Tavily search parameters to override init-time values. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The search results as Haystack Documents. | | `links` | List[str] | The URLs of the search results. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("TAVILY_API_KEY")` | The Tavily API key. | | `top_k` | Optional[int] | 10 | The maximum number of search results to return. | | `search_params` | Optional[Dict[str, Any]] | None | Additional Tavily API parameters, such as `search_depth` (`"basic"` or `"advanced"`), `include_domains`, `exclude_domains`, `include_answer`, and `include_raw_content`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The search query to send to Tavily. | | `search_params` | Optional[Dict[str, Any]] | None | Additional Tavily search parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## TikaDocumentConverter Convert files of various types to documents you can index into a document store. This component uses Apache Tika for parsing, which supports a wide range of file formats. Apache Tika supports a wide range of formats: - Document formats: Ms Office (DOCX, XLSX, PPTX, PPT, RTF), OpenDocument (ODT, ODS, ODP), PDF (with text extraction, no OCR), Markup languages (HTML, XML, XHTML, Markdown), Plain text (TXT, CSV, TSV) - Archive formats: ZIP, RAR, 7Z, TAR, GZIP, BZIP2 - Email formats: MDG, EML, MBOX, PST, OST To see the full list, see the [Tika documentation](https://tika.apache.org/1.30/formats.html). :::note Limitations - No OCR support. - Requires a running Tika server. ::: ## Key Features - Converts a wide range of file formats using Apache Tika. - Especially useful for archive formats (ZIP, RAR, 7Z) and email formats (EML, MSG) not supported by other converters. - Configurable Tika server URL. - Can be combined with `DocumentJoiner` to merge output from multiple converters. ## Configuration 1. Drag the `TikaDocumentConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `tika_url` to point to your running Tika server (for example, `http://localhost:9998/tika`). For more options on running Tika, see the [Tika official documentation](https://github.com/apache/tika-docker/blob/main/README.md#usage). 4. Go to the **Advanced** tab to configure `store_full_path`. ## Connections `TikaDocumentConverter` receives files from `FileTypeRouter`. It sends converted documents to `DocumentJoiner`, which is useful if you have multiple converters in your pipeline and want to join their output. ## Source Code To check this component's source code, open [`tika.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/converters/tika.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TikaDocumentConverter: type: haystack.components.converters.tika.TikaDocumentConverter init_parameters: tika_url: http://localhost:9998/tika store_full_path: false ``` 1. Drag the `TikaDocumentConverter` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Configure the parameters as needed. ## Connections `TikaDocumentConverter` accepts a list of file paths or `ByteStream` objects as input. It outputs a list of converted Haystack documents. Connect `FileTypeRouter` to its `sources` input for multi-format indexing. Connect its `documents` output to `DocumentJoiner` to merge with output from other converters, or directly to `DocumentSplitter`. ## Usage Example In this index, `TikaDocumentConverter` handles multiple file types including documents, archives, and various formats that other converters might not support. ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv - application/zip - application/x-rar-compressed - application/x-7z-compressed - message/rfc822 - application/vnd.ms-outlook additional_mimetypes: application/vnd.openxmlformats-officedocument.wordprocessingml.document: .docx application/vnd.openxmlformats-officedocument.presentationml.presentation: .pptx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: .xlsx application/x-rar-compressed: .rar application/x-7z-compressed: .7z message/rfc822: .eml application/vnd.ms-outlook: .msg TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: {} HTMLToDocument: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: markdown target_language: include_tables: true include_links: true DOCXToDocument: type: haystack.components.converters.docx.DOCXToDocument init_parameters: link_format: markdown PPTXToDocument: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: store_full_path: false XLSXToDocument: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: store_full_path: false CSVToDocument: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 store_full_path: false TikaDocumentConverter: type: haystack.components.converters.tika.TikaDocumentConverter init_parameters: tika_url: http://localhost:9998/tika store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: {} DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 1000 split_overlap: 200 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: host: localhost port: 9200 username: admin password: type: env_var env_vars: - OPENSEARCH_PASSWORD strict: false index: documents embedding_dim: 768 similarity: cosine connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PDFMinerToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: FileTypeRouter.text/html receiver: HTMLToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: DOCXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: PPTXToDocument.sources - sender: FileTypeRouter.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: XLSXToDocument.sources - sender: FileTypeRouter.text/csv receiver: CSVToDocument.sources - sender: FileTypeRouter.application/zip receiver: TikaDocumentConverter.sources - sender: FileTypeRouter.application/x-rar-compressed receiver: TikaDocumentConverter.sources - sender: FileTypeRouter.application/x-7z-compressed receiver: TikaDocumentConverter.sources - sender: FileTypeRouter.message/rfc822 receiver: TikaDocumentConverter.sources - sender: FileTypeRouter.application/vnd.ms-outlook receiver: TikaDocumentConverter.sources - sender: FileTypeRouter.unclassified receiver: TikaDocumentConverter.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: PDFMinerToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: HTMLToDocument.documents receiver: DocumentJoiner.documents - sender: DOCXToDocument.documents receiver: DocumentJoiner.documents - sender: PPTXToDocument.documents receiver: DocumentJoiner.documents - sender: XLSXToDocument.documents receiver: DocumentJoiner.documents - sender: CSVToDocument.documents receiver: DocumentJoiner.documents - sender: TikaDocumentConverter.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | List of file paths or ByteStream objects to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter |Type| Default | Description | |---------------|----|--------------------------|---------------------------------------------------------------------------------------------------------------------| |tika_url |str |http://localhost:9998/tika|Tika server URL. | |store_full_path|bool|False |If `True`, the full path of the file is stored in the metadata of the document. If `False`, only the file name is stored.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|-----------------------------------------------------|-------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |sources |List[Union[str, Path, ByteStream]] | |List of file paths or ByteStream objects to convert. | |meta |Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]|None |Optional metadata to attach to the documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of sources, because the two lists will be zipped. If `sources` contains ByteStream objects, their `meta` will be added to the output Documents.| --- ## TogetherAIChatGenerator Generate text using large language models hosted on Together AI. For supported models, see [Together AI documentation](https://docs.together.ai/docs). ## Key Features - Supports all chat completion models available through Together AI. - Accepts all parameters supported by the Together AI chat completion endpoint via `generation_kwargs`. - Supports tool calling with Haystack tools and Toolsets. - Supports streaming responses token by token. ## Configuration 1. Drag the `TogetherAIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your Together AI account on the Integrations page. For detailed instructions, see [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx). - Select the model to use. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, `max_retries`, and `http_client_kwargs`. ## Connections `TogetherAIChatGenerator` receives rendered chat prompts from `ChatPromptBuilder` through its `messages` input. It sends generated replies through its `replies` output to downstream components such as `OutputAdapter` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/togetherai/src/haystack_integrations/components/generators/togetherai/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml TogetherAIChatGenerator: type: haystack_integrations.components.generators.togetherai.chat.chat_generator.TogetherAIChatGenerator init_parameters: api_key: type: env_var env_vars: - TOGETHER_API_KEY strict: false model: meta-llama/Llama-3.3-70B-Instruct-Turbo api_base_url: https://api.together.xyz/v1 ``` This is an example RAG pipeline with `TogetherAIChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false TogetherAIChatGenerator: type: haystack_integrations.components.generators.togetherai.chat.chat_generator.TogetherAIChatGenerator init_parameters: api_key: type: env_var env_vars: - TOGETHER_API_KEY strict: false model: meta-llama/Llama-3.3-70B-Instruct-Turbo streaming_callback: api_base_url: https://api.together.xyz/v1 generation_kwargs: tools: timeout: max_retries: http_client_kwargs: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: TogetherAIChatGenerator.messages - sender: TogetherAIChatGenerator.replies receiver: OutputAdapter.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when the LLM receives a new token from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization. | | `tools_strict` | Optional[bool] | Whether to enable strict schema adherence for tool calls. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |api_key|Secret|Secret.from_env_var('TOGETHER_API_KEY')|The Together AI API key.| |model|str|meta-llama/Llama-3.3-70B-Instruct-Turbo|The name of the Together AI chat completion model to use.| |streaming_callback|Optional[StreamingCallbackT]|None|A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument.| |api_base_url|Optional[str]|https://api.together.xyz/v1|The Together AI API base URL. For more details, see [Together AI documentation](https://docs.together.ai/docs/openai-api-compatibility).| |generation_kwargs|Optional[Dict[str, Any]]|None|Other parameters to use for the model. These parameters are sent directly to the Together AI endpoint. See [Together AI API documentation](https://docs.together.ai/reference/chat-completions-1) for more details. Supported parameters include: `max_tokens` (maximum number of tokens the output text can have), `temperature` (sampling temperature for creativity control), `top_p` (nucleus sampling probability mass), `stream` (whether to stream back partial progress), `safe_prompt` (whether to inject a safety prompt before all conversations), `random_seed` (the seed to use for random sampling), `response_format` (a JSON schema or Pydantic model that enforces the structure of the model's response).| |tools|Optional[Union[List[Tool], Toolset]]|None|A list of tools or a Toolset for which the model can prepare calls. Each tool should have a unique name.| |timeout|Optional[float]|None|The timeout for the Together AI API call.| |max_retries|Optional[int]|None|Maximum number of retries to contact Together AI after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable or five.| |http_client_kwargs|Optional[Dict[str, Any]]|None|A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |messages|List[ChatMessage]||A list of `ChatMessage` instances representing the input messages.| |streaming_callback|Optional[StreamingCallbackT]|None|A callback function called when a new token is received from the stream.| |generation_kwargs|Optional[Dict[str, Any]]|None|Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration.| |tools|Optional[Union[List[Tool], Toolset]]|None|A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization.| |tools_strict|Optional[bool]|None|Whether to enable strict schema adherence for tool calls.| ## Related Information - [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## TogetherAIGenerator Generate text using large language models running on Together AI. This component provides a simple interface for text generation without the chat message format. ## Key Features - Supports all text completion models available through Together AI. - Accepts all parameters supported by the Together AI API via `generation_kwargs`. - Supports optional system prompts for context or instructions. - Supports streaming responses token by token. - Returns generated text as strings along with metadata. ## Configuration 1. Drag the `TogetherAIGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your Together AI account on the Integrations page. For detailed instructions, see [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx). - Select the model to use. - Optionally, set a system prompt. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, and `max_retries`. ## Connections `TogetherAIGenerator` receives a rendered prompt string from `PromptBuilder`. It sends generated replies to `AnswerBuilder` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/togetherai/src/haystack_integrations/components/generators/togetherai/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml TogetherAIGenerator: type: haystack_integrations.components.generators.togetherai.generator.TogetherAIGenerator init_parameters: api_key: type: env_var env_vars: - TOGETHER_API_KEY strict: false model: meta-llama/Llama-3.3-70B-Instruct-Turbo api_base_url: https://api.together.xyz/v1 ``` This is an example RAG pipeline with `TogetherAIGenerator` and `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n\nProvided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" TogetherAIGenerator: type: haystack_integrations.components.generators.togetherai.generator.TogetherAIGenerator init_parameters: api_key: type: env_var env_vars: - TOGETHER_API_KEY strict: false model: meta-llama/Llama-3.3-70B-Instruct-Turbo streaming_callback: api_base_url: https://api.together.xyz/v1 system_prompt: generation_kwargs: timeout: max_retries: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: TogetherAIGenerator.prompt - sender: TogetherAIGenerator.replies receiver: answer_builder.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "PromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `prompt` | str | The input prompt string for text generation. | | `system_prompt` | Optional[str] | An optional system prompt to provide context or instructions for the generation. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[str] | A list of generated text completions as strings. | | `meta` | List[Dict[str, Any]] | A list of metadata dictionaries containing information about each generation, including model name, finish reason, and token usage statistics. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |api_key|Secret|Secret.from_env_var('TOGETHER_API_KEY')|The Together AI API key.| |model|str|meta-llama/Llama-3.3-70B-Instruct-Turbo|The name of the model to use.| |api_base_url|Optional[str]|https://api.together.xyz/v1|The base URL of the Together AI API.| |streaming_callback|Optional[StreamingCallbackT]|None|A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument.| |system_prompt|Optional[str]|None|The system prompt to use for text generation. If not provided, the system prompt is omitted and the default system prompt of the model is used.| |generation_kwargs|Optional[Dict[str, Any]]|None|Other parameters to use for the model. These parameters are sent directly to the Together AI endpoint. See [Together AI documentation](https://docs.together.ai/reference/chat-completions-1) for more details. Supported parameters include: `max_tokens` (maximum number of tokens the output text can have), `temperature` (sampling temperature for creativity control), `top_p` (nucleus sampling probability mass), `n` (number of completions to generate for each prompt), `stop` (sequences after which the LLM should stop generating tokens), `presence_penalty` (penalty for tokens already present), `frequency_penalty` (penalty for frequently generated tokens), `logit_bias` (add logit bias to specific tokens).| |timeout|Optional[float]|None|Timeout for Together AI client calls. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30.| |max_retries|Optional[int]|None|Maximum retries to establish contact with Together AI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to five.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |prompt|str||The input prompt string for text generation.| |system_prompt|Optional[str]|None|An optional system prompt to provide context or instructions for the generation. If not provided, the system prompt set during initialization is used.| |streaming_callback|Optional[StreamingCallbackT]|None|A callback function called when a new token is received from the stream. If provided, this overrides the `streaming_callback` set during initialization.| |generation_kwargs|Optional[Dict[str, Any]]|None|Additional keyword arguments for text generation. These parameters override the parameters passed during initialization. Supported parameters include `temperature`, `max_tokens`, `top_p`, and others.| ## Related Information - [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## TransformersChatGenerator Generate chat responses using transformer models from Hugging Face that run locally. Use this component when you want to run open-source LLMs on your own hardware without external API calls. ## Key Features - Runs Hugging Face `transformers` models locally for fully offline operation. - Supports text-generation, text2text-generation, and image-text-to-text pipeline tasks. - Supports tool calling with a configurable tool parsing function. - Supports streaming responses through a configurable callback. - Supports extended thinking mode (for example, for Qwen3 models). - Configurable device placement (CPU, GPU, or automatic). ## Configuration 1. Drag the `TransformersChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Hugging Face model you want to use (for example, `Qwen/Qwen3-0.6B` or `meta-llama/Llama-2-7b-chat-hf`). 2. If the model requires authentication, create a secret with your Hugging Face API token and set it as `token`. Use `HF_API_TOKEN` or `HF_TOKEN` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs` such as `max_new_tokens`, `temperature`, and `do_sample`. :::note LLMs running locally may need powerful hardware. Ensure your deployment environment has sufficient GPU or CPU resources for the model you choose. ::: ## Connections `TransformersChatGenerator` receives a list of `ChatMessage` objects as input, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/transformers/src/haystack_integrations/components/generators/transformers/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml TransformersChatGenerator: type: haystack_integrations.components.generators.transformers.chat.chat_generator.TransformersChatGenerator init_parameters: model: Qwen/Qwen3-0.6B generation_kwargs: max_new_tokens: 512 temperature: 0.7 do_sample: true ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: system content: You are a helpful assistant. Answer questions based on the provided documents. - role: user content: | Documents: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ question }} llm: type: haystack_integrations.components.generators.transformers.chat.chat_generator.TransformersChatGenerator init_parameters: model: Qwen/Qwen3-0.6B token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: max_new_tokens: 512 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question documents: - prompt_builder.documents outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `Qwen/Qwen3-0.6B` | The Hugging Face model name or path to use. | | `task` | Optional[str] | None | The pipeline task. One of `text-generation`, `text2text-generation`, or `image-text-to-text`. If None, the task is inferred from the model. | | `device` | Optional[ComponentDevice] | None | The device to run the model on. If None, uses the default device. | | `token` | Optional[Secret] | `Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False)` | A Hugging Face API token for accessing gated or private models. | | `chat_template` | Optional[str] | None | A custom Jinja2 chat template string. If None, uses the model's default template. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters such as `max_new_tokens`, `temperature`, `do_sample`, and `top_p`. | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments passed directly to the Hugging Face `pipeline()` constructor. | | `stop_words` | Optional[List[str]] | None | A list of stop words that cause generation to stop early. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses token by token. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use. | | `tool_parsing_function` | Optional[Callable] | None | A custom function to parse tool call strings from the model output. | | `enable_thinking` | bool | `False` | Whether to enable extended thinking mode. Supported by models like Qwen3. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters to override init-time values. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model, overriding init-time tools. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## https://unstructured.io/FileConverter Convert files to Haystack Documents using the [Unstructured.io](https://unstructured.io/) API (hosted or running locally). For supported file types and API parameters, see [Unstructured.io docs](https://docs.unstructured.io/api-reference/api-services/overview). ## Key Features - Supports a wide range of file types via the Unstructured.io API. - Works with both the hosted Unstructured.io API and a locally running instance. - Configurable document creation mode: one document per file, per page, or per element. - Configurable separator for concatenating elements. - Supports passing additional parameters to the Unstructured.io API. ## Configuration 1. Drag the `UnstructuredFileConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `UNSTRUCTURED_API_KEY` secret in your workspace if using the hosted API. For instructions, see [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). If you run the API locally, an API key is not needed. - Set the `api_url`. If using the hosted API, you can leave this as the default. If running locally, set it to your local API URL (for example, `http://localhost:8000/general/v0/general`). - Choose the `document_creation_mode`. 4. Go to the **Advanced** tab to configure `unstructured_kwargs`, `separator`, and `progress_bar`. ## Connections `UnstructuredFileConverter` receives file paths as input. It sends converted documents to downstream processing components like `DocumentSplitter` or `DocumentWriter`. ## Source Code To check this component's source code, open [`converter.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/unstructured/src/haystack_integrations/components/converters/unstructured/converter.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml UnstructuredFileConverter: type: haystack_integrations.components.converters.unstructured.converter.UnstructuredFileConverter init_parameters: api_key: type: env_var env_vars: - UNSTRUCTURED_API_KEY strict: false ``` Connect the pipeline's file path input to its `paths` input. Connect its `documents` output to a `DocumentSplitter` or `DocumentWriter`. ```yaml # haystack-pipeline components: unstructured_converter: type: haystack_integrations.components.converters.unstructured.converter.UnstructuredFileConverter init_parameters: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `paths` | Union[List[str], List[os.PathLike]] | List of paths to convert. Paths can be files or directories. If a path is a directory, all files in the directory are converted. Subdirectories are ignored. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of paths, because the two lists will be zipped. Note that if the paths contain directories, `meta` can only be a single dictionary (same metadata for all files). | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of Haystack Documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------------|----------------------------------------------------------------------|---------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |api_url |str |UNSTRUCTURED_HOSTED_API_URL |URL of the Unstructured.io API. Defaults to the URL of the hosted version. If you run the API locally, specify the URL of your local API (for example, `"http://localhost:8000/general/v0/general"`). | |api_key |Optional[Secret] |Secret.from_env_var('UNSTRUCTURED_API_KEY', strict=False)|API key for the Unstructured.io API. It can be explicitly passed or read from the environment variable `UNSTRUCTURED_API_KEY` (recommended). If you run the API locally, it is not needed. | |document_creation_mode|Literal['one-doc-per-file', 'one-doc-per-page', 'one-doc-per-element']|one-doc-per-file |How to create Haystack Documents from the elements returned by Unstructured.io. `"one-doc-per-file"`: One Haystack Document per file. All elements are concatenated into one text field. `"one-doc-per-page"`: One Haystack Document per page. All elements on a page are concatenated into one text field. `"one-doc-per-element"`: One Haystack Document per element. Each element is converted to a Haystack Document.| |separator |str |\n\n |Separator between elements when concatenating them into one text field. | |unstructured_kwargs |Optional[Dict[str, Any]] |None |Additional parameters that are passed to the Unstructured.io API. For the available parameters, see [Unstructured.io API docs](https://docs.unstructured.io/api-reference/api-services/api-parameters). | |progress_bar |bool |True |Whether to show a progress bar during the conversion. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|-----------------------------------------------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |paths |Union[List[str], List[os.PathLike]] | |List of paths to convert. Paths can be files or directories. If a path is a directory, all files in the directory are converted. Subdirectories are ignored. | |meta |Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]|None |Optional metadata to attach to the Documents. This value can be either a list of dictionaries or a single dictionary. If it's a single dictionary, its content is added to the metadata of all produced Documents. If it's a list, the length of the list must match the number of paths, because the two lists will be zipped. Please note that if the paths contain directories, `meta` can only be a single dictionary (same metadata for all files).| ## Related Information - [Add Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx) --- ## VLLMChatGenerator Generate chat responses using models served with [vLLM](https://docs.vllm.ai/). ## Key Features - Works with any model served by a vLLM server using the OpenAI-compatible API. - Accepts and returns messages in `ChatMessage` format. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Supports reasoning models with the `extra_body` parameter. - Uses the OpenAI-compatible API, so the same component works with any vLLM-served model. ## Configuration 1. Drag the `VLLMChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the model name served by your vLLM instance (for example, `Qwen/Qwen3-4B-Instruct`). 2. Set the `api_base_url` to your vLLM server address. The default is `http://localhost:8000/v1`. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `timeout`, `max_retries`, and `tools`. ## Connections `VLLMChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/vllm/src/haystack_integrations/components/generators/vllm/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VLLMChatGenerator: type: haystack_integrations.components.generators.vllm.VLLMChatGenerator init_parameters: model: Qwen/Qwen3-4B-Instruct api_base_url: http://localhost:8000/v1 generation_kwargs: temperature: 0.7 max_tokens: 1024 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: "Answer the following question: {{ question }}" llm: type: haystack_integrations.components.generators.vllm.VLLMChatGenerator init_parameters: model: Qwen/Qwen3-4B-Instruct api_base_url: http://localhost:8000/v1 generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The name of the model served by the vLLM instance. | | `api_key` | Optional[Secret] | `Secret.from_env_var("VLLM_API_KEY", strict=False)` | An API key for authenticated vLLM deployments. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. | | `api_base_url` | str | `http://localhost:8000/v1` | The URL of the vLLM server's OpenAI-compatible API. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters such as `temperature`, `max_tokens`, and `top_p`. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for tool calling. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the HTTP client. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## VLLMDocumentEmbedder Compute embeddings for a list of documents using embedding models served with [vLLM](https://docs.vllm.ai/). Use this component in indexing pipelines to prepare documents for embedding-based retrieval. ## Key Features - Works with any embedding model served by a vLLM server using the OpenAI-compatible Embeddings API. - Stores the computed embedding in each document's `embedding` field. - Supports adding metadata fields to the text before embedding. - Configurable batch size for efficient processing. - Supports vLLM-specific parameters through `extra_parameters`. ## Configuration 1. Drag the `VLLMDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the embedding model served by your vLLM instance. 2. Set the `api_base_url` to your vLLM server address. The default is `http://localhost:8000/v1`. 4. Go to the **Advanced** tab to configure `batch_size`, `meta_fields_to_embed`, `embedding_separator`, `prefix`, and `suffix`. ## Connections `VLLMDocumentEmbedder` receives a list of documents, typically from a document splitter or converter. It outputs the same documents with embeddings added to their `embedding` field, ready to be sent to a `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/vllm/src/haystack_integrations/components/embedders/vllm/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VLLMDocumentEmbedder: type: haystack_integrations.components.embedders.vllm.VLLMDocumentEmbedder init_parameters: model: BAAI/bge-large-en-v1.5 api_base_url: http://localhost:8000/v1 batch_size: 32 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: VLLMDocumentEmbedder: type: haystack_integrations.components.embedders.vllm.VLLMDocumentEmbedder init_parameters: model: BAAI/bge-large-en-v1.5 api_base_url: http://localhost:8000/v1 batch_size: 32 meta_fields_to_embed: embedding_separator: "\n" document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 1024 connections: - sender: VLLMDocumentEmbedder.documents receiver: document_writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents with their `embedding` field populated. | | `meta` | Dict[str, Any] | Metadata about the embedding request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The name of the embedding model served by the vLLM instance. | | `api_key` | Optional[Secret] | `Secret.from_env_var("VLLM_API_KEY", strict=False)` | An API key for authenticated vLLM deployments. | | `api_base_url` | str | `http://localhost:8000/v1` | The URL of the vLLM server's OpenAI-compatible API. | | `prefix` | str | `""` | A string to add at the beginning of each document's text before embedding. | | `suffix` | str | `""` | A string to add at the end of each document's text before embedding. | | `dimensions` | Optional[int] | None | The number of dimensions in the output embedding. | | `batch_size` | int | 32 | The number of documents to process in each batch. | | `progress_bar` | bool | True | Whether to show a progress bar during embedding. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text before embedding. | | `embedding_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the HTTP client. | | `raise_on_failure` | bool | False | Whether to raise an exception on individual document embedding failures. | | `extra_parameters` | Optional[Dict[str, Any]] | None | Additional vLLM-specific parameters for the embedding request. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## VLLMRanker Rank documents by their similarity to a query using reranking models served with [vLLM](https://docs.vllm.ai/). ## Key Features - Reranks documents based on semantic similarity to the query using the vLLM `/rerank` endpoint. - Works with any reranking model served by a vLLM server. - Returns documents sorted from most to least relevant. - Configurable `top_k` and `score_threshold` to control the number and quality of results. - Can include metadata fields in the document text for ranking. ## Configuration 1. Drag the `VLLMRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the reranking model served by your vLLM instance. 2. Set the `api_base_url` to your vLLM server address. The default is `http://localhost:8000/v1`. 4. Go to the **Advanced** tab to configure `top_k`, `score_threshold`, and `meta_fields_to_embed`. ## Connections `VLLMRanker` receives a query string and a list of documents from a retriever. It outputs a reranked list of documents, sorted by relevance to the query. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/vllm/src/haystack_integrations/components/rankers/vllm/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VLLMRanker: type: haystack_integrations.components.rankers.vllm.VLLMRanker init_parameters: model: BAAI/bge-reranker-v2-m3 api_base_url: http://localhost:8000/v1 top_k: 5 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: top_k: 20 document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index VLLMRanker: type: haystack_integrations.components.rankers.vllm.VLLMRanker init_parameters: model: BAAI/bge-reranker-v2-m3 api_base_url: http://localhost:8000/v1 top_k: 5 connections: - sender: retriever.documents receiver: VLLMRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - VLLMRanker.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query to rank documents against. | | `documents` | List[Document] | A list of documents to rerank. | | `top_k` | Optional[int] | The maximum number of documents to return. Overrides the init-time `top_k`. | | `score_threshold` | Optional[float] | Minimum score threshold. Overrides the init-time `score_threshold`. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The reranked documents, sorted from most to least relevant. | | `meta` | Dict[str, Any] | Metadata about the reranking request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The name of the reranking model served by the vLLM instance. | | `api_key` | Optional[Secret] | `Secret.from_env_var("VLLM_API_KEY", strict=False)` | An API key for authenticated vLLM deployments. | | `api_base_url` | str | `http://localhost:8000/v1` | The URL of the vLLM server's API. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `score_threshold` | Optional[float] | None | A minimum score threshold. Documents below this score are filtered out. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text when scoring. | | `meta_data_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the HTTP client. | | `extra_parameters` | Optional[Dict[str, Any]] | None | Additional vLLM-specific parameters for the reranking request. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The query to rank documents against. | | `documents` | List[Document] | | A list of documents to rerank. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `score_threshold` | Optional[float] | None | Minimum score threshold for results. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## VLLMTextEmbedder Embed strings using embedding models served with [vLLM](https://docs.vllm.ai/). Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Works with any embedding model served by a vLLM server using the OpenAI-compatible Embeddings API. - Outputs a float vector embedding suitable for use with embedding retrievers. - Supports vLLM-specific parameters through `extra_parameters`. - The embedding model must match the one used by `VLLMDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `VLLMTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the embedding model served by your vLLM instance. 2. Set the `api_base_url` to your vLLM server address. The default is `http://localhost:8000/v1`. 4. Go to the **Advanced** tab to configure `dimensions`, `prefix`, `suffix`, and `extra_parameters`. ## Connections `VLLMTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/vllm/src/haystack_integrations/components/embedders/vllm/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml VLLMTextEmbedder: type: haystack_integrations.components.embedders.vllm.VLLMTextEmbedder init_parameters: model: BAAI/bge-large-en-v1.5 api_base_url: http://localhost:8000/v1 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: VLLMTextEmbedder: type: haystack_integrations.components.embedders.vllm.VLLMTextEmbedder init_parameters: model: BAAI/bge-large-en-v1.5 api_base_url: http://localhost:8000/v1 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 1024 connections: - sender: VLLMTextEmbedder.embedding receiver: retriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - VLLMTextEmbedder.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | | `meta` | Dict[str, Any] | Metadata about the request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | *(required)* | The name of the embedding model served by the vLLM instance. | | `api_key` | Optional[Secret] | `Secret.from_env_var("VLLM_API_KEY", strict=False)` | An API key for authenticated vLLM deployments. | | `api_base_url` | str | `http://localhost:8000/v1` | The URL of the vLLM server's OpenAI-compatible API. | | `prefix` | str | `""` | A string to add at the beginning of the text before embedding. | | `suffix` | str | `""` | A string to add at the end of the text before embedding. | | `dimensions` | Optional[int] | None | The number of dimensions in the output embedding, if the model supports it. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the HTTP client. | | `extra_parameters` | Optional[Dict[str, Any]] | None | Additional vLLM-specific parameters for the embedding request. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text to embed. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## VoyageDocumentEmbedder Compute document embeddings using Voyage AI embedding models. Use this component in indexes to embed documents before storing them in a vector database. ## Key Features - Computes dense vector embeddings for documents using Voyage AI models. - Supports configurable input types (`document` or `query`) for optimized embeddings. - Embeds documents in configurable batch sizes for efficient processing. - Supports configurable output dimension and data type. - Optionally embeds metadata fields along with document content. ## Configuration 1. Drag the `VoyageDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your Voyage AI account on the Integrations page. For detailed instructions, see [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx). - Select the embedding model to use. - Set `input_type` to `"document"` for indexing documents. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `output_dimension`, `output_dtype`, `prefix`, `suffix`, and metadata embedding options. ## Connections `VoyageDocumentEmbedder` receives documents to embed from PreProcessors like `DocumentSplitter`. It sends documents with embeddings to `DocumentWriter` to write them into a document store. ## Usage Examples ### Basic Configuration ```yaml document_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_document_embedder.VoyageDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: voyage-3 input_type: document truncate: true output_dtype: float batch_size: 32 embedding_separator: "\n" progress_bar: true ``` This is an example index with `VoyageDocumentEmbedder` for document embedding: ```yaml # haystack-pipeline components: converter: type: haystack.components.converters.multi_file_converter.MultiFileConverter init_parameters: encoding: utf-8 cleaner: type: haystack.components.preprocessors.document_cleaner.DocumentCleaner init_parameters: remove_empty_lines: true remove_extra_whitespaces: true remove_repeated_substrings: false keep_id: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 split_threshold: 0 document_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_document_embedder.VoyageDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: voyage-3 input_type: document truncate: true prefix: suffix: output_dimension: output_dtype: float batch_size: 32 metadata_fields_to_embed: embedding_separator: "\n" progress_bar: true timeout: max_retries: writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: converter.documents receiver: cleaner.documents - sender: cleaner.documents receiver: splitter.documents - sender: splitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents with embeddings stored in the `embedding` field. | | `meta` | Dict[str, Any] | Metadata about the embedding operation. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |api_key|Secret|Secret.from_env_var('VOYAGE_API_KEY')|The Voyage AI API key. It can be explicitly provided or automatically read from the environment variable VOYAGE_API_KEY.| |model|str|voyage-3|The name of the Voyage model to use. See the [Voyage Embeddings documentation](https://docs.voyageai.com/embeddings/) for available models.| |input_type|Optional[str]|None|Type of the input text. Set to `"document"` for indexing documents or `"query"` for search queries. When set, prepends an appropriate prompt to the text.| |truncate|bool|True|Whether to truncate the input text to fit within the context length. If `False`, an error is raised when the text exceeds the context length.| |prefix|str|""|A string to add to the beginning of each text.| |suffix|str|""|A string to add to the end of each text.| |output_dimension|Optional[int]|None|The dimension of the output embedding. Only supported by `voyage-3-large` and `voyage-code-3` models.| |output_dtype|str|float|The data type for the embeddings. Options: "float", "int8", "uint8", "binary", "ubinary".| |batch_size|int|32|Number of documents to encode at once.| |metadata_fields_to_embed|Optional[List[str]]|None|List of metadata fields to embed along with the document content.| |embedding_separator|str|"\n"|Separator used to concatenate metadata fields to the document content.| |progress_bar|bool|True|Whether to show a progress bar during processing.| |timeout|Optional[int]|None|Timeout for Voyage AI client calls. If not set, it is inferred from the `VOYAGE_TIMEOUT` environment variable or set to 30.| |max_retries|Optional[int]|None|Maximum retries if Voyage AI returns an internal error. If not set, it is inferred from the `VOYAGE_MAX_RETRIES` environment variable or set to five.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |documents|List[Document]||A list of documents to embed.| ## Related Information - [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## VoyageRanker Rank documents by relevance to a query using Voyage AI reranking models. Rerankers are typically used after initial retrieval (like BM25 or embedding-based retrieval) to refine the results before passing them to a language model. ## Key Features - Reranks retrieved documents by relevance using Voyage AI's reranking models. - Configurable number of results with `top_k`. - Supports configurable text prefix and suffix for preprocessing. - Optionally embeds metadata fields along with document content for ranking. - Configurable timeout and retry behavior. ## Configuration 1. Drag the `VoyageRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your Voyage AI account on the Integrations page. For detailed instructions, see [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx). - Select the reranking model to use. - Set `top_k` to control the number of ranked documents to return. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `truncate`, `meta_fields_to_embed`, and `meta_data_separator`. ## Connections `VoyageRanker` receives a query string and a list of documents from retrievers like `OpenSearchBM25Retriever`. It sends ranked documents to `PromptBuilder` or downstream components for answer generation. ## Usage Examples ### Basic Configuration ```yaml ranker: type: haystack_integrations.components.rankers.voyage.ranker.VoyageRanker init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: rerank-2 top_k: 8 meta_data_separator: "\n" ``` This is an example RAG pipeline with `VoyageRanker` for document reranking: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 50 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 50 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack_integrations.components.rankers.voyage.ranker.VoyageRanker init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: rerank-2 truncate: top_k: 8 prefix: suffix: timeout: max_retries: meta_fields_to_embed: meta_data_separator: "\n" meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n\nProvided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: max_tokens: 1000 temperature: 0.7 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: generator.messages - sender: generator.replies receiver: answer_builder.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "PromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query to rank documents against. | | `documents` | List[Document] | A list of documents to rank. | | `top_k` | Optional[int] | Maximum number of documents to return. Overrides the value set at initialization. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Documents ranked by relevance, sorted from most to least relevant. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |api_key|Secret|Secret.from_env_var('VOYAGE_API_KEY')|The Voyage AI API key. It can be explicitly provided or automatically read from the environment variable VOYAGE_API_KEY.| |model|str|rerank-2|The name of the Voyage reranking model to use. See the [Voyage Rerankers documentation](https://docs.voyageai.com/docs/reranker) for available models.| |truncate|Optional[bool]|None|Whether to truncate the input text to fit within the context length. If `None`, truncates slightly over-length text but raises an error for significantly over-length text.| |top_k|Optional[int]|None|The number of most relevant documents to return. If not specified, returns all documents.| |prefix|str|""|A string to add to the beginning of each text.| |suffix|str|""|A string to add to the end of each text.| |timeout|Optional[int]|None|Timeout for Voyage AI client calls. If not set, it is inferred from the `VOYAGE_TIMEOUT` environment variable or set to 30.| |max_retries|Optional[int]|None|Maximum retries if Voyage AI returns an internal error. If not set, it is inferred from the `VOYAGE_MAX_RETRIES` environment variable or set to five.| |meta_fields_to_embed|Optional[List[str]]|None|List of metadata fields to include when ranking documents.| |meta_data_separator|str|"\n"|Separator used to concatenate metadata fields to the document content.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |query|str||The query to rank documents against.| |documents|List[Document]||A list of documents to rank.| |top_k|Optional[int]|None|Maximum number of documents to return. Overrides the value set at initialization.| ## Related Information - [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## VoyageTextEmbedder Embed text, such as user queries, using Voyage AI embedding models. Use this component in query pipelines when you want to perform semantic search. ## Key Features - Embeds text strings (queries) using Voyage AI models optimized for retrieval. - Supports configurable input types (`query` or `document`) for optimized embeddings. - Supports configurable output dimension and data type. - Configurable prefix and suffix for text preprocessing. ## Configuration 1. Drag the `VoyageTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to your Voyage AI account on the Integrations page. For detailed instructions, see [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx). - Select the embedding model to use. - Set `input_type` to `"query"` for search queries. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `output_dimension`, `output_dtype`, `prefix`, and `suffix`. ## Connections `VoyageTextEmbedder` receives text to embed from the `Input` component. It sends the embedding to embedding-based retrievers like `OpenSearchEmbeddingRetriever`. ## Usage Examples ### Basic Configuration ```yaml query_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_text_embedder.VoyageTextEmbedder init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: voyage-3 input_type: query truncate: true output_dtype: float ``` This is an example RAG pipeline with `VoyageTextEmbedder` for query embedding: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: haystack_integrations.components.embedders.voyage_embedders.voyage_text_embedder.VoyageTextEmbedder init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: voyage-3 input_type: query truncate: true prefix: suffix: output_dimension: output_dtype: float timeout: max_retries: embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack_integrations.components.rankers.voyage.ranker.VoyageRanker init_parameters: api_key: type: env_var env_vars: - VOYAGE_API_KEY strict: false model: rerank-2 top_k: 8 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n\nProvided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: max_tokens: 1000 temperature: 0.7 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: answer_builder.documents - sender: ranker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: generator.messages - sender: generator.replies receiver: answer_builder.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "PromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the input text. | | `meta` | Dict[str, Any] | Metadata related to the embedding operation. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: |Parameter|Type|Default|Description| |---------|----|-------|-----------| |api_key|Secret|Secret.from_env_var('VOYAGE_API_KEY')|The Voyage AI API key. It can be explicitly provided or automatically read from the environment variable VOYAGE_API_KEY.| |model|str|voyage-3|The name of the Voyage model to use. See the [Voyage Embeddings documentation](https://docs.voyageai.com/embeddings/) for available models.| |input_type|Optional[str]|None|Type of the input text. Set to `"query"` for search queries or `"document"` for documents. When set, prepends an appropriate prompt to the text.| |truncate|bool|True|Whether to truncate the input text to fit within the context length. If `False`, an error is raised when the text exceeds the context length.| |prefix|str|""|A string to add to the beginning of the text.| |suffix|str|""|A string to add to the end of the text.| |output_dimension|Optional[int]|None|The dimension of the output embedding. Only supported by `voyage-3-large` and `voyage-code-3` models.| |output_dtype|str|float|The data type for the embeddings. Options: "float", "int8", "uint8", "binary", "ubinary".| |timeout|Optional[int]|None|Timeout for Voyage AI client calls. If not set, it is inferred from the `VOYAGE_TIMEOUT` environment variable or set to 30.| |max_retries|Optional[int]|None|Maximum retries if Voyage AI returns an internal error. If not set, it is inferred from the `VOYAGE_MAX_RETRIES` environment variable or set to five.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default|Description| |---------|----|-------|-----------| |text|str||The text to embed.| ## Related Information - [Use Voyage AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-voyage-ai.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## WatsonxChatGenerator Generate chat responses using IBM watsonx.ai foundation models. ## Key Features - Supports IBM's foundation models available on watsonx.ai, including Granite and Llama models. - Accepts and returns messages in `ChatMessage` format. - Supports multimodal inputs with text and images. - Supports streaming responses through a configurable callback. - Supports tool calling for agentic workflows. - Configurable IBM Cloud region through `api_base_url`. ## Configuration 1. Drag the `WatsonxChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the watsonx.ai model you want to use (for example, `ibm/granite-4-h-small`). For a full list, see the [IBM watsonx.ai documentation](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx). 2. Create secrets for your watsonx.ai credentials. Use `WATSONX_API_KEY` for the API key and `WATSONX_PROJECT_ID` for the project ID. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `generation_kwargs`, `api_base_url`, `timeout`, and `tools`. ## Connections `WatsonxChatGenerator` receives a list of `ChatMessage` objects, typically from `PromptBuilder` or `ChatPromptBuilder`. It outputs a list of reply `ChatMessage` objects you can connect to `AnswerBuilder` or other downstream components. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/watsonx/src/haystack_integrations/components/generators/watsonx/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WatsonxChatGenerator: type: haystack_integrations.components.generators.watsonx.chat.WatsonxChatGenerator init_parameters: api_key: type: env_var env_vars: - WATSONX_API_KEY strict: false project_id: type: env_var env_vars: - WATSONX_PROJECT_ID strict: false model: ibm/granite-4-h-small api_base_url: https://us-south.ml.cloud.ibm.com generation_kwargs: max_tokens: 1024 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: required_variables: "*" template: - role: user content: "Answer the following question: {{ question }}" llm: type: haystack_integrations.components.generators.watsonx.chat.WatsonxChatGenerator init_parameters: api_key: type: env_var env_vars: - WATSONX_API_KEY strict: false project_id: type: env_var env_vars: - WATSONX_PROJECT_ID strict: false model: ibm/granite-4-h-small generation_kwargs: max_tokens: 1024 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 metadata: {} inputs: query: - answer_builder.query - prompt_builder.question outputs: answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `messages` | List[ChatMessage] | A list of chat messages representing the conversation so far. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `replies` | List[ChatMessage] | A list of generated reply messages from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("WATSONX_API_KEY")` | The IBM Cloud API key for watsonx.ai. | | `model` | str | `ibm/granite-4-h-small` | The name of the watsonx.ai foundation model. For a full list, see the [IBM documentation](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx). | | `project_id` | Secret | `Secret.from_env_var("WATSONX_PROJECT_ID")` | The watsonx.ai project ID. | | `api_base_url` | str | `https://us-south.ml.cloud.ibm.com` | The IBM Cloud watsonx.ai API base URL. Change the region prefix (for example, `eu-de`) to use a different IBM Cloud region. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional generation parameters for the watsonx.ai API, such as `max_tokens`, `temperature`, `top_p`, and `stop_sequences`. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | | `verify` | Optional[Union[bool, str]] | None | SSL certificate verification setting. | | `streaming_callback` | Optional[Callable] | None | A callback function for streaming responses. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for tool calling. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `messages` | List[ChatMessage] | | A list of chat messages representing the conversation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Generation parameters to override init-time values. | | `streaming_callback` | Optional[Callable] | None | A callback function to override the init-time streaming callback. | | `tools` | Optional[List[Tool]] | None | Tools to make available to the model. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## WatsonxDocumentEmbedder Compute embeddings for a list of documents using IBM watsonx.ai embedding models. Use this component in indexing pipelines to prepare documents for embedding-based retrieval. ## Key Features - Uses IBM watsonx.ai embedding models such as `ibm/slate-30m-english-rtrvr-v2`. - Stores the computed embedding in each document's `embedding` field. - Supports high-throughput processing with configurable batch size and concurrency. - Supports adding metadata fields to the text before embedding. ## Configuration 1. Drag the `WatsonxDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the watsonx.ai embedding model you want to use. 2. Create secrets for your watsonx.ai credentials: `WATSONX_API_KEY` and `WATSONX_PROJECT_ID`. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `batch_size`, `concurrency_limit`, `meta_fields_to_embed`, and `truncate_input_tokens`. ## Connections `WatsonxDocumentEmbedder` receives a list of documents, typically from a document splitter or converter. It outputs the same documents with embeddings added to their `embedding` field, ready to be sent to a `DocumentWriter`. ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/watsonx/src/haystack_integrations/components/embedders/watsonx/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WatsonxDocumentEmbedder: type: haystack_integrations.components.embedders.watsonx.WatsonxDocumentEmbedder init_parameters: api_key: type: env_var env_vars: - WATSONX_API_KEY strict: false project_id: type: env_var env_vars: - WATSONX_PROJECT_ID strict: false model: ibm/slate-30m-english-rtrvr-v2 batch_size: 1000 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of documents to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The documents with their `embedding` field populated. | | `meta` | Dict[str, Any] | Metadata about the embedding request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `ibm/slate-30m-english-rtrvr-v2` | The name of the watsonx.ai embedding model. | | `api_key` | Secret | `Secret.from_env_var("WATSONX_API_KEY")` | The IBM Cloud API key for watsonx.ai. | | `api_base_url` | str | `https://us-south.ml.cloud.ibm.com` | The IBM Cloud watsonx.ai API base URL. | | `project_id` | Secret | `Secret.from_env_var("WATSONX_PROJECT_ID")` | The watsonx.ai project ID. | | `truncate_input_tokens` | Optional[int] | None | The maximum number of input tokens. Text exceeding this limit is truncated. | | `prefix` | str | `""` | A string to add at the beginning of each document's text before embedding. | | `suffix` | str | `""` | A string to add at the end of each document's text before embedding. | | `batch_size` | int | 1000 | The number of documents to process in each batch. | | `concurrency_limit` | int | 5 | The maximum number of concurrent API requests. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | | `meta_fields_to_embed` | Optional[List[str]] | None | A list of document metadata field names to include in the text before embedding. | | `embedding_separator` | str | `"\n"` | The separator used to join the document text and metadata fields. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `documents` | List[Document] | | A list of documents to embed. | ## Related Information - [WatsonxTextEmbedder](/docs/reference/pipeline-components/integrations/watsonx/WatsonxTextEmbedder.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## WatsonxTextEmbedder Embed strings using IBM watsonx.ai embedding models. Use this component in query pipelines to transform user queries into vectors for embedding-based retrieval. ## Key Features - Uses IBM watsonx.ai embedding models such as `ibm/slate-30m-english-rtrvr-v2`. - Outputs a float vector embedding suitable for use with embedding retrievers. - The embedding model must match the one used by `WatsonxDocumentEmbedder` in the indexing pipeline. ## Configuration 1. Drag the `WatsonxTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the same watsonx.ai embedding model used in your indexing pipeline. 2. Create secrets for your watsonx.ai credentials: `WATSONX_API_KEY` and `WATSONX_PROJECT_ID`. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `truncate_input_tokens`, and `api_base_url`. ## Connections `WatsonxTextEmbedder` receives the user query as a text string, typically from the `Input` component. It outputs a float vector through its `embedding` output, which you connect to an embedding retriever. ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/watsonx/src/haystack_integrations/components/embedders/watsonx/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WatsonxTextEmbedder: type: haystack_integrations.components.embedders.watsonx.WatsonxTextEmbedder init_parameters: api_key: type: env_var env_vars: - WATSONX_API_KEY strict: false project_id: type: env_var env_vars: - WATSONX_PROJECT_ID strict: false model: ibm/slate-30m-english-rtrvr-v2 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: WatsonxTextEmbedder: type: haystack_integrations.components.embedders.watsonx.WatsonxTextEmbedder init_parameters: api_key: type: env_var env_vars: - WATSONX_API_KEY strict: false project_id: type: env_var env_vars: - WATSONX_PROJECT_ID strict: false model: ibm/slate-30m-english-rtrvr-v2 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: top_k: 10 document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: my-index embedding_dim: 384 connections: - sender: WatsonxTextEmbedder.embedding receiver: retriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - WatsonxTextEmbedder.text ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `text` | str | The text to embed. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `embedding` | List[float] | The embedding of the text. | | `meta` | Dict[str, Any] | Metadata about the request. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `ibm/slate-30m-english-rtrvr-v2` | The name of the watsonx.ai embedding model. | | `api_key` | Secret | `Secret.from_env_var("WATSONX_API_KEY")` | The IBM Cloud API key for watsonx.ai. | | `api_base_url` | str | `https://us-south.ml.cloud.ibm.com` | The IBM Cloud watsonx.ai API base URL. | | `project_id` | Secret | `Secret.from_env_var("WATSONX_PROJECT_ID")` | The watsonx.ai project ID. | | `truncate_input_tokens` | Optional[int] | None | The maximum number of input tokens. Text exceeding this limit is truncated. | | `prefix` | str | `""` | A string to add at the beginning of the text before embedding. | | `suffix` | str | `""` | A string to add at the end of the text before embedding. | | `timeout` | Optional[float] | None | Request timeout in seconds. | | `max_retries` | Optional[int] | None | Maximum number of retries on API errors. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `text` | str | | The text to embed. | ## Related Information - [WatsonxDocumentEmbedder](/docs/reference/pipeline-components/integrations/watsonx/WatsonxDocumentEmbedder.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## WeaveConnector Collect traces from your pipeline and send them to Weights & Biases (W&B). Use this component to integrate with the Weights & Biases Weave framework. ## Key Features - Sends pipeline traces to Weights & Biases Weave for analysis. - No connections to other pipeline components required — just add it to your pipeline. - Configurable pipeline name used as the Weave project name in W&B. - Supports additional Weave initialization options via `weave_init_kwargs`. ## Configuration 1. Drag the `WeaveConnector` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Connect to W&B through the Integrations page. For details, see [Use Weights & Biases Services](/docs/how-to-guides/productionizing-your-pipeline/use-weights-and-biases.mdx). - Set `pipeline_name` to the name of the pipeline you want to trace. This is used as the Weave project name in W&B. 4. Go to the **Advanced** tab to configure `weave_init_kwargs` if needed. ## Connections `WeaveConnector` doesn't connect to any other component. Add it to your pipeline without connecting it to other components. ## Source Code To check this component's source code, open [`weave_connector.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weave/src/haystack_integrations/components/connectors/weave/weave_connector.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WeaveConnector: type: haystack_integrations.components.connectors.weave.weave_connector.WeaveConnector init_parameters: pipeline_name: RAG-Chat ``` In this example, `WeaveConnector` is added to a RAG-Chat pipeline. It's in the query pipeline but is not connected to any other component. It's sending the traces of the RAG-Chat pipeline to Weights & Biases: And here's the YAML configuration of the pipeline: ```yaml # haystack-pipeline components: chat_summary_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are part of a chatbot. You receive a question (Current Question) and a chat history. Use the context from the chat history and reformulate the question so that it is suitable for retrieval augmented generation. If X is followed by Y, only ask for Y and do not repeat X again. If the question does not require any context from the chat history, output it unedited. Don't make questions too long, but short and precise. Stay as close as possible to the current question. Only output the new question, nothing else! {{ question }} New question: chat_summary_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 replies_to_query: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: "{{ replies[0] }}" output_type: str bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 # The number of results to return query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: "intfloat/e5-base-v2" embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 qa_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: qa_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm WeaveConnector: type: haystack_integrations.components.connectors.weave.weave_connector.WeaveConnector init_parameters: pipeline_name: RAG-Chat connections: # Defines how the components are connected - sender: chat_summary_prompt_builder.prompt receiver: chat_summary_llm.prompt - sender: chat_summary_llm.replies receiver: replies_to_query.replies - sender: replies_to_query.output receiver: bm25_retriever.query - sender: replies_to_query.output receiver: query_embedder.text - sender: replies_to_query.output receiver: ranker.query - sender: replies_to_query.output receiver: qa_prompt_builder.question - sender: replies_to_query.output receiver: answer_builder.query - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: qa_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: qa_prompt_builder.prompt receiver: qa_llm.prompt - sender: qa_prompt_builder.prompt receiver: answer_builder.prompt - sender: qa_llm.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "chat_summary_prompt_builder.question" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs This component takes no inputs. ### Outputs This component produces no outputs. ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type |Default| Description | |-----------------|---------------------|-------|-------------------------------------------| |pipeline_name |str | |The name of the pipeline you want to trace. Used as the name of the Weave project in W&B. We recommend setting it to the name of the pipeline you're tracing. This will make it easier to identify where the traces come from, especially when managing multiple projects.| |weave_init_kwargs|dict[str, Any] \| None| None |Additional keyword arguments for Weave. | ### Run Method Parameters This component has no `run()` method parameters. ## Related Information - [Use Weights & Biases Services](/docs/how-to-guides/productionizing-your-pipeline/use-weights-and-biases.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## WeaviateBM25Retriever Retrieve documents from a Weaviate document store using the BM25 algorithm for keyword-based search. ## Key Features - Keyword-based BM25 retrieval from a Weaviate vector database. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `WeaviateBM25Retriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `WeaviateDocumentStore` with your Weaviate instance URL. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy` and default filters. ## Connections `WeaviateBM25Retriever` receives a query text string as input. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`bm25_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/bm25_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WeaviateBM25Retriever: type: haystack_integrations.components.retrievers.weaviate.bm25_retriever.WeaviateBM25Retriever init_parameters: {} ``` Connect the pipeline's query input to its `query` input. Connect its `documents` output to a `PromptBuilder`, `Ranker`, or answer builder. ```yaml # haystack-pipeline components: WeaviateBM25Retriever: type: haystack_integrations.components.retrievers.weaviate.bm25_retriever.WeaviateBM25Retriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The query text. | | `filters` | Optional[Dict[str, Any]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. | | `top_k` | Optional[int] | The maximum number of documents to return. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|------------------------|--------------------|------------------------------------------------------------------------| |document_store|WeaviateDocumentStore | |Instance of WeaviateDocumentStore that will be used from this retriever.| |filters |Optional[Dict[str, Any]]|None |Custom filters applied when running the retriever. | |top_k |int | 10|Maximum number of documents to return. | |filter_policy |Union[str, FilterPolicy]|FilterPolicy.REPLACE|Policy to determine how filters are applied. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query |str | |The query text. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. See init method docstring for more details.| |top_k |Optional[int] |None |The maximum number of documents to return. | --- ## WeaviateEmbeddingRetriever Retrieve documents from a Weaviate document store using vector search to find similar documents based on the embeddings of the query. ## Key Features - Embedding-based vector retrieval from a Weaviate vector database. - Configurable number of results with `top_k`. - Supports metadata filtering to narrow down the search space. - Supports distance and certainty thresholds for controlling result quality. - Configurable filter policy (`replace` or `merge`) for runtime filters. ## Configuration 1. Drag the `WeaviateEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `WeaviateDocumentStore` with your Weaviate instance URL. - Set `top_k` to control the maximum number of documents to retrieve. 4. Go to the **Advanced** tab to configure `filter_policy`, `distance`, `certainty`, and default filters. ## Connections `WeaviateEmbeddingRetriever` receives query embeddings from a text embedder. It sends retrieved documents to downstream components such as `PromptBuilder` or a ranker. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WeaviateEmbeddingRetriever: type: haystack_integrations.components.retrievers.weaviate.embedding_retriever.WeaviateEmbeddingRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: WeaviateEmbeddingRetriever: type: haystack_integrations.components.retrievers.weaviate.embedding_retriever.WeaviateEmbeddingRetriever init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query_embedding` | List[float] | Embedding of the query. | | `filters` | Optional[Dict[str, Any]] | Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. | | `top_k` | Optional[int] | The maximum number of documents to return. | | `distance` | Optional[float] | The maximum allowed distance between Documents' embeddings. | | `certainty` | Optional[float] | Normalized distance between the result item and the search vector. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | Retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|------------------------|--------------------|------------------------------------------------------------------------| |document_store|WeaviateDocumentStore | |Instance of WeaviateDocumentStore that will be used from this retriever.| |filters |Optional[Dict[str, Any]]|None |Custom filters applied when running the retriever. | |top_k |int | 10|Maximum number of documents to return. | |distance |Optional[float] |None |The maximum allowed distance between Documents' embeddings. | |certainty |Optional[float] |None |Normalized distance between the result item and the search vector. | |filter_policy |Union[str, FilterPolicy]|FilterPolicy.REPLACE|Policy to determine how filters are applied. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type |Default| Description | |---------------|------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |query_embedding|List[float] | |Embedding of the query. | |filters |Optional[Dict[str, Any]]|None |Filters applied to the retrieved Documents. The way runtime filters are applied depends on the `filter_policy` chosen at retriever initialization. See init method docstring for more details.| |top_k |Optional[int] |None |The maximum number of documents to return. | |distance |Optional[float] |None |The maximum allowed distance between Documents' embeddings. | |certainty |Optional[float] |None |Normalized distance between the result item and the search vector. | --- ## WeaviateHybridRetriever Retrieve documents from a `WeaviateDocumentStore` using Weaviate's native hybrid search, which combines BM25 keyword matching with dense vector search. Use this component in query pipelines to benefit from both lexical and semantic retrieval. ## Key Features - Uses Weaviate's built-in hybrid search API for seamless BM25 + vector fusion. - Configurable `alpha` parameter to blend between keyword and vector search. - Optionally filter results by maximum vector distance. - Supports async execution via `run_async`. - Configurable filter policy to merge or replace filters at query time. ## Configuration 1. First, configure a `WeaviateDocumentStore` in your pipeline. 2. Drag the `WeaviateHybridRetriever` component onto the canvas from the Component Library. 3. Set `alpha` to control the blend between keyword (`0.0`) and vector (`1.0`) search. The default is `0.7`, which favors vector search. 4. Connect both a `query` string and a `query_embedding` (from a text embedder) to the retriever. ## Connections `WeaviateHybridRetriever` receives a text `query` string and a `query_embedding` (list of floats) from a text embedder. It outputs a list of `Document` objects you can connect to `PromptBuilder` or other downstream components. ## Source Code To check this component's source code, open [`hybrid_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/hybrid_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml WeaviateHybridRetriever: type: haystack_integrations.components.retrievers.weaviate.hybrid_retriever.WeaviateHybridRetriever init_parameters: document_store: WeaviateDocumentStore top_k: 10 alpha: 0.7 ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 document_store: type: haystack_integrations.document_stores.weaviate.document_store.WeaviateDocumentStore init_parameters: url: type: env_var env_vars: - WEAVIATE_URL strict: false auth_client_secret: type: env_var env_vars: - WEAVIATE_API_KEY strict: false retriever: type: haystack_integrations.components.retrievers.weaviate.hybrid_retriever.WeaviateHybridRetriever init_parameters: document_store: document_store top_k: 10 alpha: 0.5 connections: - sender: text_embedder.embedding receiver: retriever.query_embedding inputs: query: - text_embedder.text - retriever.query outputs: documents: retriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `query` | str | The text query to search for. Used for BM25 keyword matching. | | `query_embedding` | List[float] | The query embedding vector. Used for vector similarity search. | | `filters` | Optional[Dict[str, Any]] | Filters to apply when retrieving documents. | | `top_k` | Optional[int] | The maximum number of documents to retrieve. Overrides the init-time value. | | `alpha` | Optional[float] | The blend factor between keyword and vector search. Overrides the init-time value. | | `max_vector_distance` | Optional[float] | The maximum vector distance threshold. Overrides the init-time value. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | A list of hybrid search results from Weaviate. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `document_store` | WeaviateDocumentStore | | The Weaviate document store to retrieve documents from. | | `filters` | Optional[Dict[str, Any]] | None | Default filters to apply when retrieving documents. | | `top_k` | int | `10` | The maximum number of documents to retrieve. | | `alpha` | float | `0.7` | The blend factor between keyword (`0.0`) and vector (`1.0`) search. Values between `0.0` and `1.0` blend both approaches. | | `max_vector_distance` | Optional[float] | None | The maximum allowed vector distance. Results with greater distance are excluded. | | `filter_policy` | FilterPolicy | `FilterPolicy.REPLACE` | How to handle filters passed at query time. `REPLACE` replaces init-time filters; `MERGE` combines them. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `query` | str | | The text query for keyword matching. | | `query_embedding` | List[float] | | The query embedding for vector search. | | `filters` | Optional[Dict[str, Any]] | None | Runtime filters to apply. | | `top_k` | Optional[int] | None | Maximum number of documents to retrieve. Overrides the init-time value. | | `alpha` | Optional[float] | None | Blend factor override for this query. | | `max_vector_distance` | Optional[float] | None | Maximum vector distance override for this query. | ## Related Information - [WeaviateBM25Retriever](/docs/reference/pipeline-components/integrations/weaviate/WeaviateBM25Retriever.mdx) - [WeaviateEmbeddingRetriever](/docs/reference/pipeline-components/integrations/weaviate/WeaviateEmbeddingRetriever.mdx) - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## LocalWhisperTranscriber Transcribe audio files using OpenAI's Whisper model running locally on your machine. ## Key Features - Transcribes audio to text using a locally downloaded Whisper model. - Supports multiple model sizes from `tiny` to `large-v3`. - Accepts audio files as file paths, `Path` objects, or `ByteStream` objects. - Returns transcriptions as Haystack `Document` objects. - Configurable device support (CPU, GPU) for inference. - Supports additional Whisper parameters like language, task, and temperature. ## Configuration 1. Drag the `LocalWhisperTranscriber` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Set the `model` to the Whisper model size you want to use. Larger models are more accurate but slower. Available sizes are: `tiny`, `tiny.en`, `base`, `base.en`, `small`, `small.en`, `medium`, `medium.en`, `large`, `large-v1`, `large-v2`, and `large-v3`. 4. Go to the **Advanced** tab to configure `device` and `whisper_params` for options like `language` and `task`. ## Connections `LocalWhisperTranscriber` receives a list of audio file sources. It outputs a list of `Document` objects containing the transcription text. Connect its `documents` output to a splitter, embedder, or other pipeline components. ## Source Code To check this component's source code, open [`whisper_local.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/whisper/src/haystack_integrations/components/audio/whisper/whisper_local.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LocalWhisperTranscriber: type: haystack_integrations.components.audio.whisper.LocalWhisperTranscriber init_parameters: model: large whisper_params: language: en ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: LocalWhisperTranscriber: type: haystack_integrations.components.audio.whisper.LocalWhisperTranscriber init_parameters: model: base whisper_params: language: en task: transcribe document_splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 connections: - sender: LocalWhisperTranscriber.documents receiver: document_splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of audio file paths, `Path` objects, or `ByteStream` objects to transcribe. | | `whisper_params` | Optional[Dict[str, Any]] | Additional parameters for the Whisper transcription, overriding init-time values. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The transcriptions as Haystack Documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `model` | str | `large` | The Whisper model size to use. Options are `tiny`, `tiny.en`, `base`, `base.en`, `small`, `small.en`, `medium`, `medium.en`, `large`, `large-v1`, `large-v2`, and `large-v3`. The `.en` variants are English-only models. | | `device` | Optional[ComponentDevice] | None | The device to run inference on. If not set, automatically detected. | | `whisper_params` | Optional[Dict[str, Any]] | None | Additional parameters passed to `whisper.transcribe()`. Supports `language` (ISO 639-1 code), `task` (`"transcribe"` or `"translate"`), `temperature`, and other Whisper options. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of audio file paths or streams to transcribe. | | `whisper_params` | Optional[Dict[str, Any]] | None | Additional parameters to override init-time values. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## RemoteWhisperTranscriber(Whisper) Transcribe audio files using OpenAI's Whisper API. ## Key Features - Transcribes audio to text using the OpenAI Whisper API — no local GPU required. - Accepts audio files as file paths, `Path` objects, or `ByteStream` objects. - Returns transcriptions as Haystack `Document` objects. - Supports language hints, prompt continuation, and temperature settings. - Supports custom API base URLs for compatible endpoints. ## Configuration 1. Drag the `RemoteWhisperTranscriber` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Create a secret with your OpenAI API key and set it as `api_key`. Use `OPENAI_API_KEY` as the environment variable name. For instructions, see [Create Secrets](/docs/how-to-guides/managing-access/add-secrets.mdx). 2. Set the `model` to the Whisper model version (for example, `whisper-1`). 4. Go to the **Advanced** tab to configure `api_base_url`, `organization`, and additional Whisper parameters like `language` and `temperature`. ## Connections `RemoteWhisperTranscriber` receives a list of audio file sources. It outputs a list of `Document` objects containing the transcription text. Connect its `documents` output to a splitter, embedder, or other pipeline components. ## Source Code To check this component's source code, open [`whisper_remote.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/whisper/src/haystack_integrations/components/audio/whisper/whisper_remote.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml RemoteWhisperTranscriber: type: haystack_integrations.components.audio.whisper.RemoteWhisperTranscriber init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: whisper-1 language: en ``` ### Using the Component in a Pipeline ```yaml # haystack-pipeline components: RemoteWhisperTranscriber: type: haystack_integrations.components.audio.whisper.RemoteWhisperTranscriber init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: whisper-1 language: en document_splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 connections: - sender: RemoteWhisperTranscriber.documents receiver: document_splitter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | A list of audio file paths, `Path` objects, or `ByteStream` objects to transcribe. | ### Outputs | Parameter | Type | Description | | :-------- | :--- | :---------- | | `documents` | List[Document] | The transcriptions as Haystack Documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `api_key` | Secret | `Secret.from_env_var("OPENAI_API_KEY")` | The OpenAI API key. | | `model` | str | `whisper-1` | The Whisper model version to use. | | `api_base_url` | Optional[str] | None | A custom API base URL for compatible endpoints. | | `organization` | Optional[str] | None | The OpenAI organization ID to use for requests. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the HTTP client. | | `language` | Optional[str] | | The language of the audio in ISO 639-1 format (for example, `en`, `de`, `fr`). Providing this can improve transcription speed and accuracy. | | `prompt` | Optional[str] | | An optional prompt to guide the model's style or continue a previous audio segment. | | `temperature` | Optional[float] | | The sampling temperature between 0 and 1. Higher values make output more random; lower values make it more focused. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :--- | :------ | :---------- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of audio file paths or streams to transcribe. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## Integrations Overview # Integrations Components Integrations components let you connect your pipeline to external providers and services. Use them when you want to swap in a hosted model, vector database, search backend, or data conversion tool without changing your pipeline design. This group includes provider-specific implementations of common building blocks such as generators, embedders, rankers, retrievers, converters, and connectors. Integrations help you choose the right backend for your use case and infrastructure, while keeping the pipeline interface consistent across providers. ## Available Integrations {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## AutoMergingRetriever Improve search results by returning complete parent documents instead of fragmented chunks when multiple related pieces match a query. ## Basic Information - Type: `haystack.components.retrievers.auto_merging_retriever.AutoMergingRetriever` - Components it can connect with: - Retrievers: `AutoMergingRetriever` can receive documents from any retriever that returns hierarchical documents. - `PromptBuilder`, `ChatPromptBuilder`, `AnswerBuilder`, or `Ranker`: `AutoMergingRetriever` can send documents to these components to be used in the prompt, answer, or ranking process. ## Inputs |Parameter| Type |Default| Description | |---------|--------------|-------|-------------------------------------------------------| |documents|List[Document]| |List of leaf documents that were matched by a retriever| ## Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|----------------------------------------------------------------| |documents|List[Document]| |List of documents (could be a mix of different hierarchy levels)| ## Overview `AutoMergingRetriever` works with a hierarchical document structure to return parent documents instead of individual chunked documents when the number of matched leaf documents exceeds a certain threshold. This is particularly useful when working with paragraphs split into multiple chunks: when several chunks from the same paragraph match your query, the complete paragraph often provides more context and value than the individual pieces alone. Here's how this Retriever works: 1. It requires documents to be organized in a tree structure. For information on how to create this structure, see `HierarchicalDocumentSplitter` documentation for how to create this structure. 2. When searching, it counts how many chunked documents under the same parent match your query. 3. If this count exceeds your defined threshold, it returns the parent document instead of the individual chunks. For example, if a parent document has three child chunks, and you set `threshold=0.5`, the retriever returns the parent document when at least two of the three chunks (2/3 = 0.66, which is > 0.5) are retrieved. You can use `AutoMergingRetriever` with the following Document Stores: - [Elasticsearch](https://haystack.deepset.ai/docs/latest/documentstore/elasticsearch) - [OpenSearch](https://haystack.deepset.ai/docs/latest/documentstore/opensearch) - [Qdrant](https://haystack.deepset.ai/docs/latest/documentstore/qdrant) ## Usage Examples ### Basic Configuration ```yaml auto_merging_retriever: type: haystack.components.retrievers.auto_merging_retriever.AutoMergingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false index: parent_documents threshold: 0.6 ``` This example shows a RAG pipeline that first retrieves leaf-level document chunks using BM25, merges them into higher-level parent documents with `AutoMergingRetriever`, constructs a prompt, and generates an answer: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false index: leaf_documents top_k: 10 auto_merging_retriever: type: haystack.components.retrievers.auto_merging_retriever.AutoMergingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false index: parent_documents threshold: 0.6 chat_prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant." _role: system - _content: - text: "Given these documents, answer the question.\nDocuments:\n{% for doc in documents %}{{ doc.content }}{% endfor %}\nQuestion: {{question}}\nAnswer:" _role: user llm: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: temperature: 0.7 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: auto_merging_retriever.documents - sender: auto_merging_retriever.documents receiver: chat_prompt_builder.documents - sender: chat_prompt_builder.prompt receiver: llm.messages - sender: llm.replies receiver: answer_builder.replies - sender: auto_merging_retriever.documents receiver: answer_builder.documents max_runs_per_component: 100 inputs: query: - bm25_retriever.query - chat_prompt_builder.question - answer_builder.query outputs: answers: answer_builder.answers metadata: {} ``` :::info Before using this pipeline, index your documents using `HierarchicalDocumentSplitter` to create the hierarchical structure. Leaf documents should be indexed in one document store (for example, `leaf_documents`), and parent documents in another (for example, `parent_documents`). ::: ## Parameters ### Init parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type |Default| Description | |--------------|-------------|------:|--------------------------------------------------------------------------------------| |document_store|DocumentStore| |DocumentStore from which to retrieve the parent documents | |threshold |float | 0.5|Threshold to decide whether the parent instead of the individual documents is returned| ### Run method parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter| Type |Default| Description | |---------|--------------|-------|-------------------------------------------------------| |documents|List[Document]| |List of leaf documents that were matched by a retriever| --- ## DeepsetNvidiaDocumentEmbedder Embed documents using embedding models by NVIDIA Triton. ## Basic Information - Type: `deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder` - Components it most often connects with: - PreProcessors: `DeepsetNvidiaDocumentEmbedder` can receive documents to embed from a PreProcessor, like `DocumentSplitter`. - `DocumentWriter`: `DeepsetNvidiaDocumentEmbedder` can send embedded documents to `DocumentWriter` that writes them into the document store. ## Inputs |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------| |documents|List[Document]| |The documents to embed.| ## Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| |documents|List[Document]| |Documents with their embeddings added to the metadata.| |meta |Dict[str, Any]| |Metadata on usage statistics.| ## Overview `NvidiaDocumentEmbedder` uses [NVIDTIA Triton](https://developer.nvidia.com/triton-inference-server) models to embed a list of documents. It then adds the computed embeddings to the document's `embedding` metadata field. This component runs on optimized hardware in , which means it doesn't work if you export it to a local Python file. If you're planning to export, use `SentenceTransformersDocumentEmbedder` instead. ## Usage Examples ### Basic Configuration ```yaml DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' batch_size: 32 embedding_separator: \n normalize_embeddings: true ``` ### Using the Component in an Index This is an example of a `DeepsetNvidiaDocumentEmbedder` used in an index. It receives a list of documents from `DocumentSplitter` and then sends the embedded documents to `DocumentWriter`: Here's the YAML configuration: ```yaml # haystack-pipeline components: DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: null DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' batch_size: 32 meta_fields_to_embed: null embedding_separator: \n truncate: null normalize_embeddings: true timeout: null backend_kwargs: null DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 1024 similarity: cosine policy: NONE connections: - sender: DocumentSplitter.documents receiver: DeepsetNvidiaDocumentEmbedder.documents - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|----------------------------|----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |DeepsetNVIDIAEmbeddingModels|DeepsetNVIDIAEmbeddingModels.INTFLOAT_MULTILINGUAL_E5_BASE|The model to use for calculating embeddings. Can be a specific model path like `intfloat/multilingual-e5-base`. Choose the model from the list. | |prefix |str | |A string to add at the beginning of each document text. Can be used to prepend the text with an instruction, as required by some embedding models, such as E5 and bge. | |suffix |str | |A string to add at the end of each document text. | |batch_size |int | 32|The number of documents to embed at once. | |meta_fields_to_embed|List[str] | None |None |List of metadata fields that should be embedded along with the document text. | |embedding_separator |str |\n |Separator used to concatenate the meta fields to the document text. | |truncate |EmbeddingTruncateMode | None|None |Specifies how to truncate inputs longer than the maximum token length. Possible options are: `START`, `END`, `NONE`. If set to `START`, the input is truncated from the start. If set to `END`, the input is truncated from the end. If set to `NONE`, returns an error if the input is too long.| |normalize_embeddings|bool |True |Whether to normalize the embeddings. Normalization is done by dividing the embedding by its L2 norm. | |timeout |float | None |None |Timeout for request calls in seconds. | |backend_kwargs |Dict[str, Any] | None |None |Keyword arguments to further customize the model behavior. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see Modify Pipeline Parameters at Query Time. |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------| |documents|List[Document]| |Documents to embed.| --- ## DeepsetNvidiaRanker Rank documents by their relevance to the query using NVIDIA Triton. ## Basic Information - Type: `deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker` - Components it most often connects to: - Retrievers: `DeepsetNvidiaRanker` can receive documents from a Retriever and then rank them. - `PromptBuilder`: `DeepsetNvidiaRanker` can send the ranked documents to `PromptBuilder`, which adds them to the prompt for the LLM. - Any component that outputs a list of documents or accepts a list of documents as input. ## Inputs | Parameter | Type |Default| Description | |------------------|--------------|-------|-------------------------------------------------------------------------------------------------------------------------------------------| |query |str | |The input query to compare the documents to. | |documents |List[Document]| |A list of documents to be ranked. | |top_k |int | None |None |The maximum number of documents to return. | |scale_score |bool | None |None |If `True`, scales the raw logit predictions using a Sigmoid activation function. If `False`, disables scaling of the raw logit predictions.| |calibration_factor|float | None |None |Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. Used only if `scale_score` is `True`. | |score_threshold |float | None |None |Use it to return documents only with a score above this threshold. | ## Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------| |documents|List[Document]| |A list of documents closest to the query, sorted from most similar to least similar.| ## Overview `DeepsetNvidiaRanker` uses the [NVIDIA Triton Inference Server](https://developer.nvidia.com/triton-inference-server) to rank documents by their similarity to the query, assigning similarity scores to each document. This component runs on optimized hardware and is usable within only, which means it doesn't work if you export it to a local Python file. If you're planning to export, use `TransformersSimilarityRanker` instead. :::info Default Model The default reranker model for new pipelines is `tomaarsen/Qwen3-Reranker-0.6B-seq-cls`. Older models (`intfloat/simlm-msmarco-reranker`, `BAAI/bge-reranker-v2-m3`, and `svalabs/cross-electra-ms-marco-german-uncased`) are no longer available for new pipelines. If your existing pipeline uses one of these models, it continues to work without any changes, and the model appears labelled as **legacy** in the model list. ::: ## Usage Example ### Basic Configuration ```yaml DeepsetNvidiaRanker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker query_prefix: '' document_prefix: '' top_k: 10 embedding_separator: \n scale_score: true calibration_factor: 1 ``` ### Using the Component in a Pipeline This is an example of a query pipeline where `DeepsetNvidiaRanker` receives documents from a `DocumentJoiner`, ranks them, and then returns them as the pipeline output. Here's the YAML configuration: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine top_k: 20 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 768 similarity: cosine top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' truncate: null normalize_embeddings: false timeout: null backend_kwargs: null DeepsetNvidiaRanker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls query_prefix: '' document_prefix: '' top_k: 10 score_threshold: null meta_fields_to_embed: null embedding_separator: \n scale_score: true calibration_factor: 1 timeout: null backend_kwargs: null connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: DeepsetNvidiaTextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: document_joiner.documents receiver: DeepsetNvidiaRanker.documents max_runs_per_component: 100 metadata: {} inputs: query: - bm25_retriever.query - DeepsetNvidiaTextEmbedder.text - DeepsetNvidiaRanker.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: DeepsetNvidiaRanker.documents ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|--------------------------|----------------------------------------------------------|----------------------------------------------------------------------------| |model |DeepsetNVIDIARankingModels|DeepsetNVIDIARankingModels.TOMAARSEN_QWEN3_RERANKER_0_6B_SEQ_CLS|The model to use for ranking. Choose the model from a list on the component card. Legacy models are labelled as **legacy** in the picker and are only available if your pipeline already uses them.| |query_prefix |str | |String to prepend to queries | |document_prefix |str | |String to prepend to documents | |top_k |int | 10|Maximum number of documents to return | |batch_size |int | 40|The number of documents to rank at once. | |score_threshold |float | None |None |Minimum score threshold for returned documents | |meta_fields_to_embed|List[str] | None |None |List of metadata fields to embed alongside the document content. | |embedding_separator |str |\n |Separator used when concatenating metadata fields with the document content.| |scale_score |bool |True |If `True`, scales raw logit predictions using a Sigmoid activation function.| |calibration_factor |float |1 |Calibration factor used with `sigmoid(logits * calibration_factor)`. Only used if `scale_score` is `True`.| |timeout |float | None |None |Timeout in seconds for the Triton inference call. | |backend_kwargs |dict | None |None |Extra keyword arguments passed to the Triton backend. | --- ## DeepsetNvidiaTextEmbedder Embed strings of text using embedding models by NVIDIA Triton on optimized hardware. ## Basic Information - Type: `deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder` - Components it most often connects with: - Input: `DeepsetNvidiaTextEmbedder` receives the query to embed from `Input`. - Embedding Retrievers: `DeepsetNvidiaTextEmbedder` can send the embedded query to an Embedding Retriever that uses it to find matching documents. ## Inputs |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |The text to embed.| ## Outputs |Parameter| Type |Default| Description | |---------|--------------|-------|------------------------------------------------------------------------------------------------------------------------------------| |embedding|List[float] | |Embedding of the text.| |meta |Dict[str, Any]| |Metadata on usage statistics.| ## Overview `NvidiaTextEmbedder` uses [NVIDIA Triton](https://developer.nvidia.com/triton-inference-server) models to embed a string, such as a query. This is useful if your pipeline performs vector-based retrieval. The Embedding Retriever can then used the embedded query to find matching documents in the document store. This component runs on optimized hardware in , which means it doesn't work if you export it to a local Python file. If you're planning to export, use SentenceTransformersTextEmbedder instead. ## Usage Examples ### Basic Configuration ```yaml DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' normalize_embeddings: true ``` ### Using the Component in a Pipeline This is an example of a `DeepsetNvidiaTextEmbedder` used in a query pipeline. It receives the text to embed from `Input` and then sends the embedded query to `OpenSearchEmbeddingRetriever`: Here's the YAML configuration: ```yaml # haystack-pipeline components: DeepsetNvidiaTextEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' truncate: null normalize_embeddings: true timeout: null backend_kwargs: null OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine filters: null top_k: 10 filter_policy: replace custom_query: null raise_on_failure: true efficient_filtering: false connections: - sender: DeepsetNvidiaTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - DeepsetNvidiaTextEmbedder.text ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|-------------------------------|----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |model |DeepsetNVIDIAEmbeddingModels |DeepsetNVIDIAEmbeddingModels.INTFLOAT_MULTILINGUAL_E5_BASE|The model to use for calculating embeddings. Choose the model from the list on the component card. | |prefix |str | |A string to add at the beginning of the string being embedded. Can be used to prepend the text with an instruction, as required by some embedding models, such as E5 and bge. | |suffix |str | |A string to add at the end of the string being embedded. | |truncate |Optional[EmbeddingTruncateMode]|None |Specifies how to truncate inputs longer than the maximum token length. Possible options are: `START`, `END`, `NONE`. If set to `START`, the input is truncated from the start. If set to `END`, the input is truncated from the end. If set to `NONE`, returns an error if the input is too long.| |normalize_embeddings|bool |True |Whether to normalize the embeddings. Normalization is done by dividing the embedding by its L2 norm. | |timeout |Optional[float] |None |Timeout for request calls in seconds. | |backend_kwargs |Optional[Dict[str, Any]] |None |Keyword arguments to further customize model behavior. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). |Parameter|Type|Default| Description | |---------|----|-------|------------------| |text |str | |The text to embed.| --- ## DeepsetOpenSearchFilterParser Parse and combine filters for use with OpenSearch. This component takes filters from the Generator's output and combines them with the filters provided at runtime. ## Basic Information - Type: `deepset_cloud_custom_nodes.augmenters.deepset_filter_parser.DeepsetOpenSearchFilterParser` - Components it can connect with: - Generators: It parses filters from the Generator's output and combines them with the filters provided at runtime. - Any component that accepts filters as input, such as Retrievers. ## Inputs | Parameter | Type |Default| Description | |----------------|-------------------------------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |replies |List[str] | |The output of a Generator. | |filters |Optional[Dict[str, Any]] |None |Optional filters to narrow down the search space to documents whose metadata meet the filter conditions. Example: ``` filters = { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, {"field": "meta.date", "operator": "<", "value": "2021-01-01"}, {"field": "meta.rating", "operator": ">=", "value": 3}, { "operator": "OR", "conditions": [ {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, ] } ] } ```| |logical_operator|Optional[Literal['AND', 'OR', 'NOT']]|None |The logical operator to use when combining the parsed filter with existing filters. | |raise_on_failure|Optional[bool] |None |Whether to raise an error if the filter cannot be parsed or converted to the OpenSearch format. If `None` is provided, the value set during initialization is used. | ## Outputs |Parameter|Type|Default|Description| |---------|----|-------|-----------| |filters |Dict| | Combined filters. | ## Overview `DeepsetOpenSearchFilterParser` combines runtime filters with filters from the Generator as follows: - Two logical filters are combined by merging their conditions. - A comparison filter and a logical filter are comibned ased on the specified logical operator. - Two comparison filters are combined into a new logical filter. Once `DeepsetOpenSearchFilterParser` receives the filters, it validates them to ensure they conform to the expected format. Each filter from the Generator must contain one comparison filter (for example, `{"field": "meta.type", "operator": "==", "value": "article"}`) or one logical filter (for example `{"operator": "AND", "conditions": [{"field": :"type", "operator": "==", "value": "article"}]}`). ## Usage Examples ### Basic Configuration ```yaml date_parser: type: deepset_cloud_custom_nodes.augmenters.deepset_filter_parser.DeepsetOpenSearchFilterParser ``` ### Using the Component in a Pipeline This is an example pipeline where we first extract the date from the LLM, then pass it to `DeepsetOpenSearchFilterParser` to ensure the date conforms to the OpenSearch format, and finally pass the date to the retrieval for filtering: ```yaml # haystack-pipeline components: chat_summary_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Rewrite the following question so that it is suitable for web search. Be cautious when reformulating. Strong changes distort the meaning of the question, which is undesirable. It is possible that the question does not need any changes. The chat history can help to incorporate context into the reformulated question. Make sure to incorporate that chat history into the revised question if needed. The meaning of the question must remain the same as before. You cannot change or dismiss keywords in the original question. If you do not want to make changes, just output the original question. Chat History: {{question}} Revised Question: chat_summary_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-4o generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 replies_to_query: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: str extract_date_template: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are part of an information system that processes user queries. When given a user query, extract dates from it and use them as values for the metadata field 'post_date_gmt'. The extracted information must be in JSON format and aligns with OpenSearch filter structure, similar to the examples below. The extracted metadata fields must be in double quotes. If you are unable to extract the dates from the query, return {}. The extracted metadata fields will be used as filters to narrow down the search space when querying an index. The extracted metadata fields must be in double quotes, and dates must follow the following format: YYYY-MM-DD. If the question requires you to know today's date for any calculations or references, use {current_datetime(format='%Y-%m-%d')} as the current date. This is particularly useful for tasks such as determining past or future dates. Note also that $gte means greater than or equal to and $lte means less than or equal to. Example 1: Query: What was the revenue of Nvidia in 2022? Extracted metadata fields: {'operator': 'AND', 'conditions': [ {'field': 'post_date_gmt', 'operator': '>=', 'value': '2022-01-01'}, {'field': 'post_date_gmt', 'operator': '<=', 'value': '2022-12-31'}]} Example 2: Query: What were the most influential publications between 2020 and 2023? Extracted metadata fields: {'operator': 'AND', 'conditions': [ {'field': 'post_date_gmt', 'operator': '>=', 'value': '2020-01-01'}, {'field': 'post_date_gmt', 'operator': '<=', 'value': '2023-12-31'}]} Example 3: Query: How did the stock market perform in the 10 days following the crash on October 29, 1929? Extracted metadata fields: {'operator': 'AND', 'conditions': [ {'field': 'post_date_gmt', 'operator': '>=', 'value': '1929-10-29'}, {'field': 'post_date_gmt', 'operator': '<=', 'value': '1929-11-08'}]} Example 4: Query: What were the key activities during the Apollo 11 mission from launch on July 16 to splashdown on July 24, 1969? Extracted metadata fields: {'operator': 'AND', 'conditions': [ {'field': 'post_date_gmt', 'operator': '>=', 'value': '1969-07-16'}, {'field': 'post_date_gmt', 'operator': '<=', 'value': '1969-07-24'}]} Example 5: Query: What were the major social events during the 2000s? Extracted metadata fields: {'operator': 'AND', 'conditions': [ {'field': 'post_date_gmt', 'operator': '>=', 'value': '2000-01-01'}, {'field': 'post_date_gmt', 'operator': '<=', 'value': '2009-12-31'}]} Example 6: After the 2008 US presidential election, what were the major US economic changes that occurred? Extracted metadata fields: {'field': 'post_date_gmt', 'operator': '>=', 'value': '2008-01-01'} Query: {{question}} Extracted metadata fields: date_extract_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 250 temperature: 0.0 seed: 0 response_format: type: "json_object" date_parser: type: deepset_cloud_custom_nodes.augmenters.deepset_filter_parser.DeepsetOpenSearchFilterParser query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: "intfloat/e5-large-v2" device: null embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: 'field': 'post_type' 'operator': '!=' 'value': 'wp_ypulse_brand' document_store: init_parameters: embedding_dim: 1024 use_ssl: True verify_certs: False http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 30 # The number of results to return reranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "intfloat/simlm-msmarco-reranker" top_k: 15 device: null model_kwargs: torch_dtype: "torch.float16" recency_ranker: type: haystack.components.rankers.meta_field.MetaFieldRanker init_parameters: meta_field: "post_date_gmt" weight: 0.8 top_k: 8 ranking_mode: linear_score sort_order: descending missing_meta: bottom qa_prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a consumer insights specialist and an expert on helping brands authentically understand young people. Your goal is to help brands better understand young people and their behaviors. You want to help brands strategically leverage the information from our corpus of content to better engage with young people. You answer questions truthfully based on provided documents. Analyze the given question, considering all relevant implications and perspectives. Provide a nuanced response that incorporates contextual background, potential outcomes, ethical considerations, and supporting evidence. You understand that other terms for young people in the documents are youth and young consumers. You understand that Gen Z and Millennials are considered young people in the documents. You understand the following rules: - 18 to 24 year olds are considered Young Adults. - 13 to 17 year olds are considered Teens. - 8 to 12 year olds are considered Tweens. Gen Z typically refers to young people either ages 13-22 years old. You understand that young POC and BIPOC refer to people that are considered Young People of Color in the documents. If asked a question about Hispanics, provide insights on young POC to answer the questions. If asked asked a question about Blacks or African-Americans, provide insights on young POC to answer the questions. If relevant information on Hispanics or African-Americans isn't available in the documents but is available for POC, provide the POC insigths and say: 'Exact insights on young Hispanics and African-Americans can be found in the YPulse Data Files'. You understand that YPulse does not have any information on Gen X, Boomers, or people over the age of 40. If information on a specific audience is not available in the documents, answer with the most relevant information for either Gen Z, Millennials, 13-39-year-olds, or all young people. Always state the names and age ranges of the audiences you reference in your response. Here's an example for how to respond: - Teens (13-17-year-olds) report using Tiktok everyday whereas Millennials only use the app twice per week. You should use the most relevant information on Gen Z if relevant information on Teens or Young Adults is not available in the documents. You should use the most relevant information on Teens or Young Adults if relevant information on Gen Z is not available in the documents. If relevant information on Students isn't available in the documents but is available for Teens or Gen Z, provide the Teens or Gen Z insights and say: 'Exact insights on Students can be found in the YPulse Data Files'. If relevant information on Parents isn't available in the documents but is available for Millennials, provide the Millennial insights and say: 'Exact insights on Parents can always be found in the YPulse Data Files'. If referencing insights captured from the YPulse Brand Tracker, cite the date range for which the data was collected. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Use data and statistics to support your answers where possible. Highlight emerging trends in consumer behavior where appropriate. Include examples of brands and products where appropriate. Ensure examples are relevant and provide clear learning points or insights. If making predictions or speculations that do not exist directly in the text, alwawys say 'YPulse AI predicts'. If making a recommendation that does not exist directly in the text, alwawys say 'YPulse AI recommends'. Recommendations should be actionable and practical considering the scale and resources for businesses or marketers. If referencing a prediction that directly exists in the text, always say 'YPulse Editorial predicts'. If referencing a recommendation that directly exists in the text, always say 'YPulse Editorial recommends'. If the question can be answered completely with a concise response and relevant statistics, you may do that. If the question requires a complex response, please provide a detailed explanation of key points on the given topic. Please format the response as follows: 1. Start with a concise these statement as an introduction. Please decide what makes most sense here. 2. Each key point should have a title. But do not limit it to three points 3. Follow the title with a well-organized paragraph explaining the point in detail. 4. Ensure the content is neatly organized in paragraphs. Here is the structure to follow: Write a short introductory paragraph teasing at the findings. **Title of Key Point One**: Write a clear and concise paragraph that elaborates on the first key point, including any relevant examples or additional information. **Title of Key Point Two**: Write a clear and concise paragraph that elaborates on the second key point, including any relevant examples or additional information. **Title of Key Point Three**: Write a clear and concise paragraph that elaborates on the third key point, including any relevant examples or additional information. (Repeat the format above for additional key points as necessary.) Ensure each section is well-structured, informative, and easy to read. You are expected to follow strict American English grammar and punctuation rules in all responses. Please ensure that you: - Use proper sentence structure and verb tenses. - Employ correct spelling and punctuation. - Apply appropriate formatting for lists, using bullet points where necessary. - Ensure that paragraphs are well-organized and that each new point begins on a new line. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document. e.g. [3], for Document[3]. The reference must only refer to the number that comes in square brackets after passage. Otherwise, do not use brackets in your answer and reference ONLY the number of the passage without mentioning the word passage. If the documents can't answer the question or you are unsure say: 'The specific answer can't be found in the YPulse text. Try rephrasing your question or check out the sources below for related content that should help.'. If you are asked about questions or survey questions that you have available or that YPulse asks in its surveys, use information from documents with post_type of wp_ypulse_question_list and please respond using the following rules: - List the survey questions in their exact format and do not summarize or paraphrase the text - Always respond with all of the questions available that match the user's query - Always include the question number or label associated with each survey question. Please use this example as reference: e.g. [H145. To what extent do you agree or disagree with the following statements about working out / fitness?] - Always use titles in the form [TITLE OF DOCUMENT] when using information from a document. e.g. NA-2024-06-12-YPulse-Behavioral-Report-Health-And-Fitness-Report, for Document[3]. - Always include the report name of the document where each question is from. Please follow this example: Here are the survey questions asked for NA-2024-06-12-YPulse-Behavioral-Report-Health-And-Fitness-Report: H145. To what extent do you agree or disagree with the following statements about working out / fitness? If referencing information published before 2024, you understand the following rules: - you must always cite the year the information was published. - you must refer to the information in past tense. Today's date is {current_datetime(format='%Y-%m-%d')}. Events before {current_datetime(format='%Y-%m-%d')} are in the past. Events after {current_datetime(format='%Y-%m-%d')} are in the future. Prioritize newer information over older information to answer the question. The publication date of a document is at the beginning of every document, compare this with today's date ({current_datetime(format='%Y-%m-%d')}) to determine the age of the document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: Title: {{ document.meta["post_title"] }} Page: {{ document.meta["page"] }} Publication Date: {{ document.meta["post_date_gmt"] }} Post type: {{ document.meta["post_type"] }} {{ document.content }} {% endfor %} Question: {{ question }} Answer: qa_llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: "gpt-4o" generation_kwargs: max_tokens: 1500 temperature: 0.0 seed: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder connections: - sender: chat_summary_prompt_builder.prompt receiver: chat_summary_llm.prompt - sender: chat_summary_llm.replies receiver: replies_to_query.replies - sender: replies_to_query.output receiver: query_embedder.text - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: replies_to_query.output receiver: extract_date_template.question - sender: extract_date_template.prompt receiver: date_extract_llm.prompt - sender: date_extract_llm.replies receiver: date_parser.replies - sender: date_parser.filters receiver: embedding_retriever.filters - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: replies_to_query.output receiver: reranker.query - sender: embedding_retriever.documents receiver: reranker.documents - sender: reranker.documents receiver: recency_ranker.documents - sender: recency_ranker.documents receiver: qa_prompt_builder.documents - sender: replies_to_query.output receiver: qa_prompt_builder.question - sender: qa_prompt_builder.prompt receiver: qa_llm.prompt - sender: qa_llm.replies receiver: answer_builder.replies - sender: qa_prompt_builder.prompt receiver: answer_builder.prompt max_loops_allowed: 100 metadata: {} inputs: query: - "chat_summary_prompt_builder.question" outputs: answers: "answer_builder.answers" documents: "recency_ranker.documents" ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type |Default| Description | |----------------|---------------------------|-------|-----------------------------------------------------------------------------------------------| |logical_operator|Literal['AND', 'OR', 'NOT']|AND |The logical operator to use when combining the parsed filter with existing filters. | |raise_on_failure|bool |False |Whether to raise an error if the filter cannot be parsed or converted to the OpenSearch format.| ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see Modify Pipeline Parameters at Query Time. | Parameter | Type |Default| Description | |----------------|-------------------------------------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |replies |List[str] | |The output of a Generator. | |filters |Optional[Dict[str, Any]] |None |Optional filters to narrow down the search space to documents whose metadata fulfill certain conditions. Example: ```filters = { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, {"field": "meta.date", "operator": "<", "value": "2021-01-01"}, {"field": "meta.rating", "operator": ">=", "value": 3}, { "operator": "OR", "conditions": [ {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, ] } ] } ```| |logical_operator|Optional[Literal['AND', 'OR', 'NOT']]|None |The logical operator to use when combining the parsed filter with existing filters. | |raise_on_failure|Optional[bool] |None |Whether to raise an error if the filter cannot be parsed or converted to the OpenSearch format. If None is provided, the value set during initialization is used. | --- ## DeepsetOpenSearchRecursiveRetriever Recursively retrieve documents from a document store based on their metadata. ## Basic Information - Type: `deepset_cloud_custom_nodes.retrievers.recursive_retriever.DeepsetOpenSearchRecursiveRetriever` - Components it can connect with: - Rankers: `DeepsetOpenSearchRecursiveRetriever` can receive documents from a Ranker. - `DocumentJoiner`: You can use `DeepsetOpenSearchRecursiveRetriever` together with another Retriever and then send the retrieved documents to a `DocumentJoiner` that combines two document lists into a single list. ## Inputs |Parameter| Type |Default| Description | |---------|------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |top_k |Optional[int] |None |The maximum number of documents to retrieve. | |documents|Optional[List[Document]]| |The documents to retrieve from. | |depth |Optional[int] |None |The depth of the recursive retrieval. For example, at depth 2, the component retrieves both the documents linked to the original documents and those linked to the retrieved documents. The default depth is 1, meaning only documents directly linked to the original documents are retrieved.| |filters |Optional[Dict[str, Any]]|None | Filters to narrow down the search. | ## Outputs |Parameter| Type |Default|Description| |---------|--------------|-------|-----------| |documents|List[Document]| | The retrieved documents. | ## Overview To use this Retriever, make sure the documents it receives include links to other documents in their metadata. `DeepsetOpenSearchRecursiveRetriever` then retrieves the linked documents and adds them to the final document list. It distinguishes between "original documents" (those initially passed to the component) and "recursively retrieved documents" (those retrieved based on the metadata of the original documents). ## Usage Examples ### Basic Configuration ```yaml DeepsetOpenSearchRecursiveRetriever: type: deepset_cloud_custom_nodes.retrievers.recursive_retriever.DeepsetOpenSearchRecursiveRetriever init_parameters: {} ``` ```yaml # haystack-pipeline components: DeepsetOpenSearchRecursiveRetriever: type: deepset_cloud_custom_nodes.retrievers.recursive_retriever.DeepsetOpenSearchRecursiveRetriever init_parameters: ``` ## Parameters ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------------------------|--------------------------------------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |filter_key |str | |The key in the document metadata that is used to identify documents for filtering. | |relevant_doc_keys |List[str] | |The keys in the document metadata that are used to retrieve relevant documents. | |document_store |OpenSearchDocumentStore | |The document store instance to retrieve documents from. | |top_k |Optional [int] | 10|The maximum number of documents the component outputs. | |depth |Optional [int] | 1|The depth of the recursive retrieval. For example, at depth 2, the component retrieves both the documents linked to the original documents and those linked to the retrieved documents. The default depth is 1, meaning only documents directly linked to the original documents are retrieved. | |sampling_strategy |Optional[List[Literal['rank', 'source', 'depth']]]|None |The sampling strategy to use for the recursive retrieval. The strategy must include the following values: [`rank`, `source`, `depth`]. `rank`: The index of the document in the list for a given metadata key. `source`: The metadata key used to retrieve the document. `depth`: The document's depth in the recursive retrieval. The default strategy is ['rank', 'source', 'depth']. The order of values determines how documents are sampled to create the final list of top_k documents. The first value has the highest priority, and the last value has the lowest. For example, with the default strategy, documents are sampled by first iterating over depth, then source, and finally rank. At each step, one document is added to the final list until the top_k number is reached. The default order of iteration will be rank0, source0, depth0, then rank0, source0, depth1, rank0, source1, depth1, and so on, until the top_k is reached.| |force_keep_original_documents|bool |False |Whether to force keeping the original documents in the final list. | |filters |Optional[Dict[str, Any]] |None | Filters to narrow down the search. | |filter_policy |Union[str, FilterPolicy] |FilterPolicy.REPLACE| The policy to determine how to apply filters. Possible values: - `REPLACE`: The filters provided at search time replace the filters in the component configuration. - `MERGE`: The filters provided at search time are merged with the filters in the component configuration. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see Modify Pipeline Parameters at Query Time. |Parameter| Type |Default| Description | |---------|------------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |top_k |Optional[int] |None |The maximum number of documents the component outputs. | |documents|Optional[List[Document]]| |The list of documents to retrieve from. | |depth |Optional[int] |None |The depth of the recursive retrieval. For example, at depth 2, the component retrieves both the documents linked to the original documents and those linked to the retrieved documents. The default depth is 1, meaning only documents directly linked to the original documents are retrieved.| |filters |Optional[Dict[str, Any]]|None | The filters to narrow down the search. | --- ## FilterRetriever Retrieve documents that match the provided filters. It's useful when you want to narrow down results based on document metadata without performing keyword or semantic search. ## Key Features - Retrieves documents based on metadata filters without keyword or semantic search. - Works with any Document Store. - Supports passing filters at query time through the API or Playground. - Returns all matching documents without scoring or ranking them. ## Configuration 1. Drag the `FilterRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Optionally, enter a filter dictionary to narrow down the search space. If you don't set filters here, the component returns all documents in the Document Store unless filters are passed at query time. 4. Go to the **Advanced** tab to configure additional settings. ## Connections `FilterRetriever` accepts an optional `filters` input, which is a dictionary that narrows down the search space. If no filters are provided at runtime, it uses the filters configured at initialization. If no filters are configured at all, it retrieves all documents in the Document Store. The component outputs `documents`, which is a list of retrieved documents. You can connect this output to components that process documents, such as a prompt builder or a ranker. Be careful when using `FilterRetriever` on a Document Store with many documents, as it returns all matching documents. Running it with no filters can easily overwhelm downstream components such as generators. `FilterRetriever` does not score or rank documents. If you need to rank documents by similarity to a query, use a Ranker component. ## Source Code To check this component's source code, open [`filter_retriever.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/retrievers/filter_retriever.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml filter_retriever: type: haystack.components.retrievers.filter_retriever.FilterRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false ``` This example shows how to use `FilterRetriever` to retrieve documents based on metadata filters: ```yaml # haystack-pipeline components: filter_retriever: type: haystack.components.retrievers.filter_retriever.FilterRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false timeout: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Given these documents, answer the question. Documents: {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{question}} Answer: llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: model: gpt-5-mini generation_kwargs: temperature: 0.7 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: filter_retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - prompt_builder.question - answer_builder.query outputs: answers: answer_builder.answers metadata: {} ``` In this example, you can pass filters at query time to narrow down the documents. For instance, to retrieve only documents from a specific year, you would pass: ```json { "filters": { "field": "year", "operator": "==", "value": 2021 } } ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | | :-------- | :----------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------ | | `filters` | Optional[Dict[str, Any]] | None | A dictionary with filters to narrow down the search space. If not specified, the FilterRetriever uses the values provided at initialization. | ### Outputs | Parameter | Type | Description | | :---------- | :------------- | :---------------------------- | | `documents` | List[Document] | A list of retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------- | :----------------------- | :------ | :-------------------------------------------------------- | | `document_store` | DocumentStore | | An instance of a Document Store to use with the Retriever. | | `filters` | Optional[Dict[str, Any]] | None | A dictionary with filters to narrow down the search space. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :-------- | :----------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------ | | `filters` | Optional[Dict[str, Any]] | None | A dictionary with filters to narrow down the search space. If not specified, the FilterRetriever uses the values provided at initialization. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) - [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx) --- ## LLMRanker Rank documents by relevance to a query using an LLM. Unlike traditional rankers that rely on similarity scoring, `LLMRanker` treats relevance as a semantic reasoning task. This can produce better results for complex or multi-step queries. The component can also filter out irrelevant or duplicate documents, helping keep context windows lean. ## Key Features - Model-agnostic: Works with any LLM. - Semantic reasoning: Treats relevance as a semantic reasoning task rather than similarity scoring. - Duplicate document filtering: Filters out irrelevant or duplicate documents. - Context window management: Helps keep context windows lean by removing low-relevance content. - Configurable fallback: Returns documents in their original order if the LLM call fails. ## Configuration 1. Drag the `LLMRanker` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Select the chat generator to use for reranking. If not set, the component uses `OpenAIChatGenerator` with `gpt-4.1-mini` by default. 4. Go to the **Advanced** tab to configure `top_k`, a custom ranking prompt, and the failure handling behavior. ## Connections `LLMRanker` accepts a `query` string, a list of candidate `documents`, and an optional `top_k` override as inputs. It outputs `documents` — the reranked list sorted from most to least relevant. Typically, you place `LLMRanker` after a retriever (such as `OpenSearchBM25Retriever`) and before a generator. Use it when your queries are complex or when you need higher-quality context in RAG pipelines. ## Source Code To check this component's source code, open [`llm_ranker.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/llm_ranker.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Configuration 1. Drag the `LLMRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, set the maximum number of documents to return (`top_k`). 4. Go to the **Advanced** tab to configure additional settings: - Set a custom `chat_generator` if you want to use a different LLM for reranking. - Optionally provide a custom `prompt` template with `query` and `documents` variables. - Set `raise_on_failure` to control error handling. ## Connections `LLMRanker` accepts a `query` string and a list of documents through its `documents` input. Connect a retriever's `documents` output to `LLMRanker`'s `documents` input, and connect the pipeline query input to `LLMRanker`'s `query` input. The component outputs a reranked `documents` list that you can pass to an LLM or another component. ## Usage Examples ### Basic Configuration ```yaml # haystack-pipeline components: LLMRanker: type: haystack.components.rankers.llm_ranker.LLMRanker init_parameters: top_k: 5 ``` This uses the default `OpenAIChatGenerator` with `gpt-4.1-mini` and the built-in ranking prompt. ### In a RAG Pipeline Use `LLMRanker` after a retriever to improve the quality of documents passed to the LLM: ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: standard-index embedding_dim: 768 return_embedding: false create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 llm_ranker: type: haystack.components.rankers.llm_ranker.LLMRanker init_parameters: top_k: 5 llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-5-mini system_prompt: "Answer the question based on the provided documents." user_prompt: |- {% message role="user" %} Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} {% endmessage %} required_variables: - documents - question AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false connections: - sender: retriever.documents receiver: llm_ranker.documents - sender: llm_ranker.documents receiver: llm.documents - sender: llm.messages receiver: AnswerBuilder.replies max_runs_per_component: 100 inputs: query: - retriever.query - llm_ranker.query - AnswerBuilder.query question: - llm.question outputs: answers: AnswerBuilder.answers ``` ### With a Custom Chat Generator You can use a different LLM for reranking by passing a custom `chat_generator`. The chat generator must return JSON output with ranked document indices. ```yaml # haystack-pipeline components: LLMRanker: type: haystack.components.rankers.llm_ranker.LLMRanker init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: temperature: 0.0 response_format: type: json_schema json_schema: name: document_ranking schema: type: object properties: documents: type: array items: type: object properties: index: type: integer required: - index additionalProperties: false required: - documents additionalProperties: false top_k: 5 ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|-----------------|---------|------------------------------------------------------------------------------------------------------| | `query` | str | | The query to rank the documents against. | | `documents` | List[Document] | | The candidate documents to rerank. | | `top_k` | Optional[int] | None | The maximum number of documents to return. Overrides the `top_k` value set during initialization. | ### Outputs | Parameter | Type | Description | |-------------|-----------------|----------------------------------------------------| | `documents` | List[Document] | The documents ranked by relevance to the query. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|-------------------------|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `chat_generator` | Optional[ChatGenerator] | None (uses `OpenAIChatGenerator` with `gpt-4.1-mini`) | The chat generator to use for reranking. If not provided, a default `OpenAIChatGenerator` configured for JSON output is used. The chat generator must return JSON with ranked document indices. | | `prompt` | str | Built-in ranking prompt | Custom prompt template for reranking. The prompt must include exactly the variables `query` and `documents` and instruct the LLM to return ranked 1-based document indices as JSON. | | `top_k` | int | 10 | The maximum number of documents to return. | | `raise_on_failure` | bool | False | If `True`, raises an error when the LLM call or response parsing fails. If `False`, logs the failure and returns the input documents in their original order as a fallback. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|-----------------|---------|------------------------------------------------------------------------------------------------------| | `query` | str | | The query to rank the documents against. | | `documents` | List[Document] | | The candidate documents to rerank. | | `top_k` | Optional[int] | None | The maximum number of documents to return. Overrides the `top_k` value set during initialization. | ## Related Information - [Pipeline Components](/docs/reference/pipeline-components/pipeline-components.mdx) --- ## MetaFieldGroupingRanker Reorder documents by grouping them based on their metadata fields. The component groups documents by a primary metadata key and optionally subgroups them with a secondary key, then outputs a flat ordered list. This helps improve the quality of context provided to LLMs by organizing documents in a structured way. ## Key Features - Groups documents by a primary metadata key (`group_by`). - Optionally subgroups documents within each group using a secondary key (`subgroup_by`). - Sorts documents within groups by a configurable metadata key (`sort_docs_by`). - Outputs a flat list ordered by group and subgroup values. - Places documents without a matching group at the end of the list. - Improves LLM performance by providing well-organized document context. ## Configuration 1. Drag the `MetaFieldGroupingRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `group_by` to the metadata key you want to group documents by (required). - Optionally set `subgroup_by` to add a secondary grouping level. 4. Go to the **Advanced** tab to set `sort_docs_by` if you want to sort documents within each group by a specific metadata key. ## Connections `MetaFieldGroupingRanker` accepts a list of documents through its `documents` input. It's typically placed after a retriever or another ranker. It outputs a reordered `documents` list, which you can send to an LLM component or another processing component. ## Source Code To check this component's source code, open [`meta_field_grouping_ranker.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/meta_field_grouping_ranker.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml # haystack-pipeline components: MetaFieldGroupingRanker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: "group" subgroup_by: "subgroup" sort_docs_by: "split_id" ``` This groups documents by the `group` metadata key, subgroups them by the `subgroup` key, and sorts them by the `split_id` key. ## Parameters ### Inputs | Parameter | Type | Default | Description | |-------------|----------------|---------|--------------------------------| | `documents` | List[Document] | | The list of documents to group. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|----------------------------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | The list of documents ordered by the `group_by` and `subgroup_by` metadata values. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------|---------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `group_by` | str | | The metadata key to aggregate the documents by. | | `subgroup_by` | Optional[str] | None | The metadata key to aggregate the documents within a group created by the `group_by` key. | | `sort_docs_by` | Optional[str] | None | Determines which metadata key is used to sort the documents. If not provided, the documents within the groups or subgroups are not sorted and are kept in the same order as they were inserted in the subgroups. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|----------------|---------|--------------------------------| | `documents` | List[Document] | | The list of documents to group. | --- ## MetaFieldRanker Rank documents based on the value of a specific metadata field. The ranking can be performed in descending or ascending order, and can be combined with scores from a previous retriever or ranker. ## Key Features - Ranks documents by the value of any numeric, integer, or date metadata field. - Supports ascending and descending sort order. - Combines metadata-based ranking with scores from the previous component using reciprocal rank fusion or linear score. - Configurable handling of documents with missing metadata (drop, place at top, or place at bottom). - Returns a configurable number of top documents. ## Configuration 1. Drag the `MetaFieldRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `meta_field` to the metadata key to rank by (required). - Set `weight` to control the balance between metadata-based ranking and the previous component's scores. - Optionally set `top_k` to limit the number of returned documents. 4. Go to the **Advanced** tab to configure `ranking_mode`, `sort_order`, `missing_meta`, and `meta_value_type`. ## Connections `MetaFieldRanker` accepts a list of documents through its `documents` input. It's typically placed after a retriever. It outputs a reranked `documents` list, which you can send to an LLM or another component. ## Source Code To check this component's source code, open [`meta_field.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/meta_field.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MetaFieldRanker: type: haystack.components.rankers.meta_field.MetaFieldRanker init_parameters: {} ``` ```yaml # haystack-pipeline components: MetaFieldRanker: type: haystack.components.rankers.meta_field.MetaFieldRanker init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |------------------|------------------------------------------------------------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | Documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return per query. If not provided, the `top_k` set during initialization is used. | | `weight` | Optional[float] | None | In range [0,1]. 0 disables ranking by a meta field. 0.5 gives equal weight to the previous component's score and the metadata ranking. 1 uses metadata ranking only. If not provided, the `weight` set during initialization is used. | | `ranking_mode` | Optional[Literal['reciprocal_rank_fusion', 'linear_score']] | None | The mode used to combine the retriever's and ranker's scores. Possible values are `reciprocal_rank_fusion` (default) and `linear_score`. Use `linear_score` only with retrievers or rankers that return a score in range [0,1]. If not provided, the `ranking_mode` set during initialization is used. | | `sort_order` | Optional[Literal['ascending', 'descending']] | None | Whether to sort the meta field by ascending or descending order. If not provided, the `sort_order` set during initialization is used. | | `missing_meta` | Optional[Literal['drop', 'top', 'bottom']] | None | What to do with documents that are missing the sorting metadata field. Possible values: `drop` drops the documents entirely; `top` places them at the top; `bottom` places them at the bottom. If not provided, the `missing_meta` set during initialization is used. | | `meta_value_type` | Optional[Literal['float', 'int', 'date']] | None | Parse the meta value into the specified data type before sorting. If not provided, the `meta_value_type` set during initialization is used. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|----------------------------------------------------------------| | `documents` | List[Document] | | List of documents sorted by the specified metadata field. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------|--------------------------------------------------|------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `meta_field` | str | | The name of the metadata field to rank by. | | `weight` | float | 1 | In range [0,1]. 0 disables ranking by a meta field. 0.5 gives equal weight to the previous component's score and the metadata ranking. 1 uses metadata ranking only. | | `top_k` | Optional[int] | None | The maximum number of documents to return per query. If not provided, the ranker returns all documents in the new ranking order. | | `ranking_mode` | Literal['reciprocal_rank_fusion', 'linear_score'] | reciprocal_rank_fusion | The mode used to combine the retriever's and ranker's scores. Possible values are `reciprocal_rank_fusion` (default) and `linear_score`. Use `linear_score` only with retrievers or rankers that return a score in range [0,1]. | | `sort_order` | Literal['ascending', 'descending'] | descending | Whether to sort the meta field by ascending or descending order. | | `missing_meta` | Literal['drop', 'top', 'bottom'] | bottom | What to do with documents that are missing the sorting metadata field. Possible values: `drop` drops the documents entirely; `top` places them at the top of the list (regardless of sort order); `bottom` places them at the bottom. | | `meta_value_type` | Optional[Literal['float', 'int', 'date']] | None | Parse the meta value into the specified data type before sorting. This only works if all meta values stored under `meta_field` in the provided documents are strings. Available options: `float`, `int`, `date` (parses into a datetime object), `None` (no parsing). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |------------------|------------------------------------------------------------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | Documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return per query. If not provided, the `top_k` set during initialization is used. | | `weight` | Optional[float] | None | In range [0,1]. 0 disables ranking by a meta field. 0.5 gives equal weight. 1 uses metadata ranking only. If not provided, the `weight` set during initialization is used. | | `ranking_mode` | Optional[Literal['reciprocal_rank_fusion', 'linear_score']] | None | The mode used to combine the retriever's and ranker's scores. If not provided, the `ranking_mode` set during initialization is used. | | `sort_order` | Optional[Literal['ascending', 'descending']] | None | Whether to sort the meta field by ascending or descending order. If not provided, the `sort_order` set during initialization is used. | | `missing_meta` | Optional[Literal['drop', 'top', 'bottom']] | None | What to do with documents that are missing the sorting metadata field. If not provided, the `missing_meta` set during initialization is used. | | `meta_value_type` | Optional[Literal['float', 'int', 'date']] | None | Parse the meta value into the specified data type before sorting. If not provided, the `meta_value_type` set during initialization is used. | --- ## MultiQueryEmbeddingRetriever Retrieve documents using multiple text queries in parallel with an embedding-based retriever. The component converts each query to an embedding, retrieves documents for each query, then combines and deduplicates the results. This improves recall by finding documents relevant to multiple query variations. ## Key Features - Processes multiple queries in parallel using an embedding-based retriever. - Deduplicates results based on document content across all queries. - Sorts the combined results by relevance score. - Configurable parallel processing with a thread pool. - Works best with `QueryExpander` to generate semantically varied query versions. ## Configuration 1. Drag the `MultiQueryEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the underlying `retriever` (an embedding-based retriever such as `OpenSearchEmbeddingRetriever`). - Configure the `query_embedder` (a text embedder to convert queries to embeddings). 4. Go to the **Advanced** tab to set `max_workers` for controlling parallel thread execution. ## Connections `MultiQueryEmbeddingRetriever` receives a list of queries through its `queries` input, typically from `QueryExpander`. It outputs a deduplicated `documents` list sorted by relevance score. Connect the `documents` output to a `Ranker`, `DocumentJoiner`, or directly to an LLM component. ## Source Code To check this component's source code, open [`multi_query_embedding_retriever.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/retrievers/multi_query_embedding_retriever.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml multi_query_retriever: type: haystack.components.retrievers.multi_query_embedding_retriever.MultiQueryEmbeddingRetriever init_parameters: query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 5 max_workers: 3 ``` ## Connections This example combines `QueryExpander` with `MultiQueryEmbeddingRetriever`. You can then send the retrieved documents to a `Ranker` or `DocumentJoiner` to combine the results: ```yaml # haystack-pipeline components: query_expander: type: haystack.components.query.query_expander.QueryExpander init_parameters: n_expansions: 3 include_original_query: true chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: {} multi_query_retriever: type: haystack.components.retrievers.multi_query_embedding_retriever.MultiQueryEmbeddingRetriever init_parameters: query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 5 max_workers: 3 connections: - sender: query_expander.queries receiver: multi_query_retriever.queries max_runs_per_component: 100 metadata: {} inputs: query: - query_expander.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :----------------- | :----------------------- | :------------------------------------------------------------------------------------------------- | | `queries` | List[str] | List of text queries to process. | | `retriever_kwargs` | Optional[Dict[str, Any]] | Optional dictionary of arguments for the retriever. | ### Outputs | Parameter | Type | Description | | :---------- | :------------- | :--------------------------------------------------------------------------------- | | `documents` | List[Document] | List of retrieved documents sorted by relevance score, deduplicated by content. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--------------- | :----------------- | :------ | :------------------------------------------------------------------------------------------------------- | | `retriever` | EmbeddingRetriever | | The embedding-based retriever to use for document retrieval. Must implement the EmbeddingRetriever protocol. | | `query_embedder` | TextEmbedder | | The query embedder to convert text queries to embeddings. Must implement the TextEmbedder protocol. | | `max_workers` | int | 3 | Maximum number of worker threads for parallel processing. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :----------------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | | `queries` | List[str] | | List of text queries to process. | | `retriever_kwargs` | Optional[Dict[str, Any]] | None | Optional dictionary of arguments to pass to the retriever's run method (for example, `filters`, `top_k`). | ## Related Information - [QueryExpander](/docs/reference/pipeline-components/knowledge-retrieval/QueryExpander.mdx) - [MultiQueryTextRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiQueryTextRetriever.mdx) --- ## MultiQueryTextRetriever Retrieve documents using multiple text queries in parallel with a text-based retriever. The component retrieves documents for each query using a thread pool, then combines and deduplicates the results. This improves recall by finding documents relevant to multiple query variations. ## Key Features - Processes multiple queries in parallel using a text-based retriever (such as BM25). - Deduplicates results based on document content across all queries. - Sorts the combined results by relevance score. - Configurable parallel processing with a thread pool. - Designed to work with `QueryExpander` for query expansion in keyword-based search. ## Configuration 1. Drag the `MultiQueryTextRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, configure the underlying `retriever` (a text-based retriever such as `OpenSearchBM25Retriever`). 4. Go to the **Advanced** tab to set `max_workers` for controlling parallel thread execution. ## Connections `MultiQueryTextRetriever` receives a list of queries through its `queries` input, typically from `QueryExpander`. It outputs a deduplicated `documents` list sorted by relevance score. Connect the `documents` output to a `Ranker`, `DocumentJoiner`, or directly to an LLM component. ## Source Code To check this component's source code, open [`multi_query_text_retriever.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/retrievers/multi_query_text_retriever.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MultiQueryTextRetriever: type: haystack.components.retrievers.multi_query_text_retriever.MultiQueryTextRetriever init_parameters: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: default ``` ## Connections This example shows how to perform retrieval with `QueryExpander` and `MultiQueryTextRetriever`. You can then send the retrieved documents to a `Ranker` or `DocumentJoiner` to combine the results: ```yaml # haystack-pipeline components: query_expander: type: haystack.components.query.query_expander.QueryExpander init_parameters: n_expansions: 3 include_original_query: true chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: {} multi_query_retriever: type: haystack.components.retrievers.multi_query_embedding_retriever.MultiQueryEmbeddingRetriever init_parameters: query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 5 max_workers: 3 connections: - sender: query_expander.queries receiver: multi_query_retriever.queries max_runs_per_component: 100 metadata: {} inputs: query: - query_expander.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :----------------- | :----------------------- | :------------------------------------------------------------------- | | `queries` | List[str] | List of text queries to process. | | `retriever_kwargs` | Optional[Dict[str, Any]] | Optional dictionary of arguments to pass to the retriever's run method. | ### Outputs | Parameter | Type | Description | | :---------- | :------------- | :------------------------------------------------------------------------------- | | `documents` | List[Document] | List of retrieved documents sorted by relevance score, deduplicated by content. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :------------ | :------------ | :------ | :------------------------------------------------------------------------------------------------- | | `retriever` | TextRetriever | | The text-based retriever to use for document retrieval. Must implement the TextRetriever protocol. | | `max_workers` | int | 3 | Maximum number of worker threads for parallel processing. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :----------------- | :----------------------- | :------ | :---------------------------------------------------------------------------------------------------------------- | | `queries` | List[str] | | List of text queries to process. | | `retriever_kwargs` | Optional[Dict[str, Any]] | None | Optional dictionary of arguments to pass to the retriever's run method (for example, `filters`, `top_k`). | ## Related Information - [QueryExpander](/docs/reference/pipeline-components/knowledge-retrieval/QueryExpander.mdx) - [MultiQueryEmbeddingRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiQueryEmbeddingRetriever.mdx) --- ## MultiRetriever Retrieve documents from multiple indexes and document stores in a single pipeline step. MultiRetriever lets you configure several knowledge sources — each with its own document store, index, and retriever strategy — and query all of them at once. The results are combined into a single list of documents passed to downstream components. ## Key Features - Query multiple indexes and document stores simultaneously. - Mix retriever strategies per source: BM25 keyword retrieval, embedding-based retrieval, or hybrid retrieval. - Select a query embedder (deepset NVIDIA, SentenceTransformers, or FastEmbed) for sources that use embedding or hybrid retrieval. - Configure each knowledge source independently with its own index and retriever type. - Automatically syncs the embedding model from the selected index when compatible. - Connect external document stores (Pinecone, Qdrant) using workspace secrets for secure credential handling. ## Configuration You configure MultiRetriever through a set of knowledge sources. Each knowledge source defines: - Document store: the backend database (for example, OpenSearch, Pinecone, or Qdrant). - Index: the specific index to query. - Retriever type: the retrieval strategy to use for this source. - Query embedder: the embedder to use when the retriever type requires embedding (for example, embedding or hybrid retrieval). ### Supported Retriever Types The available retriever types depend on the selected document store. | Retriever Type | Description | |---|---| | BM25 (keyword) | Retrieves documents using keyword-based BM25 scoring. No embedder required. | | Embedding | Retrieves documents by comparing query and document embeddings. Requires a query embedder. | | Hybrid | Combines BM25 and embedding retrieval. Requires a query embedder. | :::info SQL and metadata retrievers are not available in MultiRetriever because SQL retrieval requires per-run SQL statements and metadata retrievers return metadata rather than documents. ::: ### Query Embedder Options When you select an embedding or hybrid retriever type, you choose a query embedder for that source. The following embedders are available: | Embedder | Description | |---|---| | DeepsetNvidiaTextEmbedder | Uses NVIDIA Triton models optimized on deepset hardware. Recommended for best performance on the platform. | | SentenceTransformersTextEmbedder | Uses SentenceTransformers models. Portable — also works in exported pipelines. | | FastembedTextEmbedder | Uses FastEmbed lightweight models. Portable — also works in exported pipelines. | When you select an index, the component automatically syncs the embedding model from that index if the selected embedder is compatible. ### Adding a Knowledge Source 1. In Builder, add the **MultiRetriever** component to your pipeline. 2. Click the component to open its configuration panel. 3. Under **Knowledge Sources**, click **Add knowledge source**. 4. Choose a **Document Store** from the list. 5. Depending on the document store you selected, either choose an **Index** from the list or type the index name directly: - For OpenSearch: all available indexes are listed. If there's no available index, create one first. For details, see [Create an Index](/docs/how-to-guides/working-with-indexes/create-an-index.mdx). - For Pinecone and Qdrant: type the index name directly in the *Index* field. These document stores do not use the platform's managed indexes. 6. For Pinecone and Qdrant, fill in the required connection credentials. Each credential field supports workspace and organization secrets — start typing a secret name or select one from the dropdown. When you select a saved secret, the field shows a tag with the secret name instead of the raw value. 7. Choose the retriever to use. If the retriever type requires embedding, choose a **Query Embedder**. - *Info*: The embedding model is automatically synced from the index you chose, so that the models used to embed the query and the documents are the same. 8. Configure any extra retriever parameters shown under the retriever type selector. 9. Click **Done** to save your settings. Repeat these steps to add more sources. The component queries all configured sources when the pipeline runs. :::info If a knowledge source has required fields that are not yet filled in, the entry card shows a yellow warning indicator. The configuration drawer also opens expanded for incomplete sources so you can see what needs to be filled in. Complete all required fields before deploying the pipeline. ::: ### Editing a Knowledge Source 1. Under **Knowledge Sources**, click the knowledge source card you want to edit. 2. Update the relevant fields. 3. Click **Done** to save your changes. ## Connections - **Input**: MultiRetriever receives the query from `Input`. - **Output**: MultiRetriever sends the combined list of retrieved documents to downstream components such as a `Ranker`, `LLM`, or `Agent`. ## Source Code To check this component's source code, open [`multi_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/multi_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml MultiRetriever: type: haystack.components.retrievers.multi_retriever.MultiRetriever init_parameters: retrievers: opensearchhybrid: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: Standard-Index embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 ``` ### Using the Component in a Pipeline This example shows a RAG pipeline that queries two separate OpenSearch indexes using BM25 retrieval, then ranks and generates an answer: ```yaml # haystack-pipeline components: MultiRetriever: type: haystack.components.retrievers.multi_retriever.MultiRetriever init_parameters: retrievers: opensearchbm25: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: index-one opensearchembedding_1: type: haystack.components.retrievers.text_embedding_retriever.TextEmbeddingRetriever init_parameters: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: Standard-Index-English-aragats-15-05 text_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: model: intfloat/e5-base-v2 LLM: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: global.anthropic.claude-haiku-4-5-20251001-v1:0 user_prompt: >- {% message role="user" %} You are a technical expert. You answer questions truthfully based on provided documents. {% for doc in documents %} Document {{ loop.index }}: {{ doc.content }} {% endfor %} Question: {{ question }} {% endmessage %} required_variables: "*" system_prompt: connections: - sender: MultiRetriever.documents receiver: LLM.documents max_runs_per_component: 100 inputs: query: - MultiRetriever.query - LLM.question outputs: messages: LLM.messages metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | |---|---|---| | query | str | The query string to search for across all configured knowledge sources. | | filters | Optional[Dict[str, Any]] | Optional metadata filters to apply to all retrievers. | ### Outputs | Parameter | Type | Description | |---|---|---| | documents | List[Document] | Combined list of documents retrieved from all configured knowledge sources. | ### Init Parameters | Parameter | Type | Default | Description | |---|---|---|---| | retrievers | List[Dict] | | List of retriever configurations. Each entry defines a retriever type and its init parameters, including the document store and index to query. Configured through the knowledge sources UI in Pipeline Builder. | ### Run Method Parameters | Parameter | Type | Default | Description | |---|---|---|---| | query | str | | The query to run against all configured knowledge sources. | | filters | Optional[Dict[str, Any]] | None | Optional metadata filters to apply at query time. | | top_k_per_retriever | Optional[int] | None | The maximum number of documents to return per retriever. When set, overrides the `top_k` configured on each individual retriever. If not set, each retriever uses its own configured `top_k` value. Defaults to the value set at initialization. | | top_k | Optional[int] | None | The maximum number of documents to return overall from the combined results of all retrievers. When set, results are merged using reciprocal rank fusion to produce a consistent global ranking before being truncated to `top_k`. If not set, all results are returned. Defaults to the value set at initialization. | ## Related Information - [Knowledge Retrieval Components](/docs/reference/pipeline-components/knowledge-retrieval-overview.mdx) - [DeepsetNvidiaTextEmbedder](/docs/reference/pipeline-components/knowledge-retrieval/DeepsetNvidiaTextEmbedder.mdx) - [SentenceTransformersTextEmbedder](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersTextEmbedder.mdx) - [FastembedTextEmbedder](/docs/reference/pipeline-components/legacy-components/FastembedTextEmbedder.mdx) --- ## OpenSearchBM25Retriever(Knowledge-retrieval) Fetch documents from `OpenSearchDocumentStore` using the keyword-based BM25 algorithm. The retriever computes a weighted word overlap between the query and stored documents, making it effective for exact keyword matches such as product names, IDs, or error messages. ## Key Features - Keyword-based retrieval using the BM25 algorithm. - Configurable fuzzy matching to handle approximate string variations. - Optional filtering to narrow the search space. - Supports custom OpenSearch queries for advanced use cases. - Optionally scales document scores to a normalized range for cross-index comparison. - Option to require all query terms to be present in retrieved documents. ## Configuration 1. Drag the `OpenSearchBM25Retriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `top_k` to control the maximum number of documents to retrieve. - Optionally configure `filters` to narrow down the search space. - Set `fuzziness` to control approximate string matching (default: `AUTO`). - Optionally enable `all_terms_must_match` to require all query terms to appear in retrieved documents. 4. Go to the **Advanced** tab to configure `scale_score`, `filter_policy`, `custom_query`, and `raise_on_failure`. ## Connections `OpenSearchBM25Retriever` receives a `query` string from the `Input` component and optionally `filters`. It outputs a `documents` list. Connect the `documents` output to a `PromptBuilder`, a `Ranker`, or a `DocumentJoiner` to combine results from multiple retrievers. ## Source Code To check this component's source code, open [`bm25_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/bm25_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true similarity: cosine fuzziness: AUTO top_k: 10 scale_score: false all_terms_must_match: false filter_policy: replace raise_on_failure: true ``` ### Using the Component in a Pipeline This is an example of a simple keyword search pipeline where `OpenSearchBM25Retriever` retrieves documents matching the query. ```yaml # haystack-pipeline components: OpenSearchBM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine filters: fuzziness: AUTO top_k: 10 scale_score: false all_terms_must_match: false filter_policy: replace custom_query: raise_on_failure: true connections: [] max_runs_per_component: 100 metadata: {} inputs: query: - OpenSearchBM25Retriever.query filters: - OpenSearchBM25Retriever.filters outputs: documents: OpenSearchBM25Retriever.documents ``` ### Using in a Hybrid Search Pipeline This example shows a hybrid search pipeline that combines `OpenSearchBM25Retriever` (keyword search) with `OpenSearchEmbeddingRetriever` (semantic search). The results are joined and ranked. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine filters: fuzziness: AUTO top_k: 20 scale_score: false all_terms_must_match: false filter_policy: replace custom_query: raise_on_failure: true embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine filters: top_k: 20 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: text_embedder.embedding receiver: embedding_retriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - bm25_retriever.query - text_embedder.text filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: document_joiner.documents ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |----------------------|-------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `query` | str | | The query string. | | `filters` | Optional[Dict[str, Any]] | None | Filters applied to the retrieved documents. The way runtime filters are applied depends on the `filter_policy` specified at initialization. | | `all_terms_must_match` | Optional[bool] | None | If `True`, all terms in the query string must be present in the retrieved documents. | | `top_k` | Optional[int] | None | Maximum number of documents to return. | | `fuzziness` | Optional[Union[int, str]] | None | Fuzziness parameter for full-text queries to apply approximate string matching. For more information, see [OpenSearch fuzzy query](https://opensearch.org/docs/latest/query-dsl/term/fuzzy/). | | `scale_score` | Optional[bool] | None | If `True`, scales the score of retrieved documents to a range between 0 and 1. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query. It must include a `$query` placeholder and may optionally include a `$filters` placeholder. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|------------------------------| | `documents` | List[Document] | | List of retrieved documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |----------------------|------------------------|----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `document_store` | OpenSearchDocumentStore | | An instance of `OpenSearchDocumentStore` to use with the retriever. | | `filters` | Optional[Dict[str, Any]] | None | Filters to narrow down the search for documents in the document store. | | `fuzziness` | Union[int, str] | AUTO | Determines how approximate string matching is applied in full-text queries. This parameter sets the number of character edits (insertions, deletions, or substitutions) required to transform one word into another. Use `AUTO` (the default) for automatic adjustment based on term length. For detailed guidance, refer to the [OpenSearch fuzzy query documentation](https://opensearch.org/docs/latest/query-dsl/term/fuzzy/). | | `top_k` | int | 10 | Maximum number of documents to return. | | `scale_score` | bool | False | If `True`, scales the score of retrieved documents to a range between 0 and 1. This is useful when comparing documents across different indexes. | | `all_terms_must_match` | bool | False | If `True`, all terms in the query string must be present in the retrieved documents. This is useful when searching for short text where even one term makes a difference. | | `filter_policy` | Union[str, FilterPolicy] | FilterPolicy.REPLACE | Policy to determine how filters are applied. Possible options: `replace` — runtime filters replace initialization filters (use this to change the filtering scope for specific queries); `merge` — runtime filters are merged with initialization filters. | | `custom_query` | Optional[Dict[str, Any]] | None | The query containing a mandatory `$query` and an optional `$filters` placeholder. | | `raise_on_failure` | bool | True | Whether to raise an exception if the API call fails. If `False`, logs a warning and returns an empty list. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |----------------------|-------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `query` | str | | The query string. | | `filters` | Optional[Dict[str, Any]] | None | Filters applied to the retrieved documents. The way runtime filters are applied depends on the `filter_policy` specified at initialization. | | `all_terms_must_match` | Optional[bool] | None | If `True`, all terms in the query string must be present in the retrieved documents. | | `top_k` | Optional[int] | None | Maximum number of documents to return. | | `fuzziness` | Optional[Union[int, str]] | None | Fuzziness parameter for full-text queries to apply approximate string matching. For more information, see [OpenSearch fuzzy query](https://opensearch.org/docs/latest/query-dsl/term/fuzzy/). | | `scale_score` | Optional[bool] | None | If `True`, scales the score of retrieved documents to a range between 0 and 1. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query. It must include a `$query` placeholder and may optionally include a `$filters` placeholder. | ## Related Information - [OpenSearchEmbeddingRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchEmbeddingRetriever.mdx) - [OpenSearchHybridRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchHybridRetriever.mdx) --- ## OpenSearchEmbeddingRetriever(Knowledge-retrieval) Retrieve documents from `OpenSearchDocumentStore` using vector similarity. The retriever compares the query embedding to stored document embeddings and returns the most semantically relevant documents. ## Key Features - Semantic retrieval using vector similarity (approximate kNN search). - Requires document embeddings created by an indexing pipeline. - Supports configurable filtering during approximate kNN search. - Efficient filtering option for "faiss" and "lucene" kNN engines. - Supports custom OpenSearch queries for advanced use cases. ## Configuration 1. Drag the `OpenSearchEmbeddingRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `top_k` to control the maximum number of documents to retrieve. - Optionally configure `filters` to narrow down the search space. 4. Go to the **Advanced** tab to configure `filter_policy`, `custom_query`, `raise_on_failure`, and `efficient_filtering`. :::note Make sure the `embedding_dim` of the `OpenSearchDocumentStore` matches the dimension of the embeddings created by your embedding model. ::: ## Connections `OpenSearchEmbeddingRetriever` receives a `query_embedding` (a list of floats) from a text embedder such as `SentenceTransformersTextEmbedder`. Connect a text embedder's `embedding` output to the retriever's `query_embedding` input. The retriever outputs a `documents` list that you can send to a `PromptBuilder`, `Ranker`, or `DocumentJoiner`. ## Source Code To check this component's source code, open [`embedding_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/embedding_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: '' max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false create_index: true similarity: cosine top_k: 10 filter_policy: replace raise_on_failure: true efficient_filtering: true ``` ### Using the Component in a Pipeline This is an example of a semantic search pipeline where `OpenSearchEmbeddingRetriever` receives the query embedding from a text embedder and retrieves matching documents. ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true connections: - sender: text_embedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - text_embedder.text filters: - OpenSearchEmbeddingRetriever.filters outputs: documents: OpenSearchEmbeddingRetriever.documents ``` ### Using in a RAG Pipeline This example shows a RAG pipeline that uses `OpenSearchEmbeddingRetriever` to find relevant documents, then passes them to a generator to answer a question. ```yaml # haystack-pipeline components: text_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: sentence-transformers/all-MiniLM-L6-v2 device: token: prefix: '' suffix: '' batch_size: 32 progress_bar: true normalize_embeddings: false trust_remote_code: false retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- Given the following documents, answer the question. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ question }} Answer: generator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: true model: gpt-4o-mini generation_kwargs: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: text_embedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.prompt - sender: generator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt max_runs_per_component: 100 metadata: {} inputs: query: - text_embedder.text - prompt_builder.question - answer_builder.query filters: - retriever.filters outputs: documents: retriever.documents answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |---------------------|-------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `query_embedding` | List[float] | | Embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters applied when fetching documents. Filters are applied during the approximate kNN search to ensure the retriever returns `top_k` matching documents. The way runtime filters are applied depends on the `filter_policy` at initialization. | | `top_k` | Optional[int] | None | Maximum number of documents to return. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query containing a mandatory `$query_embedding` and an optional `$filters` placeholder. | | `efficient_filtering` | Optional[bool] | None | If `True`, the filter is applied during the approximate kNN search. Only supported for knn engines "faiss" and "lucene". | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|----------------------------------------------------| | `documents` | List[Document] | | List of documents similar to the query embedding. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |---------------------|-------------------------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `document_store` | OpenSearchDocumentStore | | An instance of `OpenSearchDocumentStore` to use with the retriever. | | `filters` | Optional[Dict[str, Any]] | None | Filters applied when fetching documents from the document store. | | `top_k` | int | 10 | Maximum number of documents to return. | | `filter_policy` | Union[str, FilterPolicy] | FilterPolicy.REPLACE | Policy to determine how filters are applied. Possible options: `merge` — runtime filters are merged with initialization filters; `replace` — runtime filters replace initialization filters. | | `custom_query` | Optional[Dict[str, Any]] | None | The custom OpenSearch query containing a mandatory `$query_embedding` and an optional `$filters` placeholder. | | `raise_on_failure` | bool | True | If `True`, raises an exception if the API call fails. If `False`, logs a warning and returns an empty list. | | `efficient_filtering` | bool | False | If `True`, the filter is applied during the approximate kNN search. Only supported for knn engines "faiss" and "lucene", not the default "nmslib". | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |---------------------|-------------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `query_embedding` | List[float] | | Embedding of the query. | | `filters` | Optional[Dict[str, Any]] | None | Filters applied when fetching documents. The way runtime filters are applied depends on the `filter_policy` set during initialization. | | `top_k` | Optional[int] | None | Maximum number of documents to return. | | `custom_query` | Optional[Dict[str, Any]] | None | A custom OpenSearch query containing a mandatory `$query_embedding` and an optional `$filters` placeholder. | | `efficient_filtering` | Optional[bool] | None | If `True`, the filter is applied during the approximate kNN search. Only supported for knn engines "faiss" and "lucene". | ## Related Information - [OpenSearchBM25Retriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchBM25Retriever.mdx) - [OpenSearchHybridRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchHybridRetriever.mdx) - [SentenceTransformersTextEmbedder](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersTextEmbedder.mdx) --- ## OpenSearchHybridRetriever(Knowledge-retrieval) Retrieve documents from OpenSearch using a combination of BM25 keyword search and embedding-based semantic search. The component runs both retrieval methods in parallel, then combines the results using a configurable join strategy. This hybrid approach typically provides better retrieval quality than using either method alone. ## Key Features - Combines BM25 keyword search and embedding-based semantic search in a single component. - Configurable join strategies: Reciprocal Rank Fusion (RRF), concatenate, merge, and distribution-based rank fusion. - Separate filter policies for BM25 and embedding retrieval. - Configurable top-k limits for each retrieval method and for the final combined result. - Built-in text embedder for converting queries to embeddings. ## Configuration 1. Drag the `OpenSearchHybridRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `embedder` (a text embedder for semantic search, such as `SentenceTransformersTextEmbedder`). - Set `top_k_bm25` and `top_k_embedding` to control the number of documents retrieved by each method. - Set `top_k` to limit the final number of combined documents returned. - Optionally configure `filters_bm25` and `filters_embedding`. 4. Go to the **Advanced** tab to configure `fuzziness`, `scale_score`, `all_terms_must_match`, `filter_policy_bm25`, `filter_policy_embedding`, `custom_query_bm25`, `custom_query_embedding`, `join_mode`, `weights`, and `sort_by_score`. ## Connections `OpenSearchHybridRetriever` receives a `query` string from the `Input` component. It outputs a `documents` list. Connect the `documents` output to a `PromptBuilder`, a `Ranker`, or directly to an LLM component. ## Source Code To check this component's source code, open [`open_search_hybrid_retriever.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/opensearch/src/haystack_integrations/components/retrievers/opensearch/open_search_hybrid_retriever.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml hybrid_retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 fuzziness: AUTO top_k_bm25: 20 scale_score: false all_terms_must_match: false filter_policy_bm25: replace top_k_embedding: 20 filter_policy_embedding: replace join_mode: reciprocal_rank_fusion top_k: 10 sort_by_score: true ``` This is an example RAG pipeline with `OpenSearchHybridRetriever` combining BM25 and embedding-based retrieval: ```yaml # haystack-pipeline components: hybrid_retriever: type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 filters_bm25: fuzziness: AUTO top_k_bm25: 20 scale_score: false all_terms_must_match: false filter_policy_bm25: replace custom_query_bm25: filters_embedding: top_k_embedding: 20 filter_policy_embedding: replace custom_query_embedding: join_mode: reciprocal_rank_fusion weights: top_k: 10 sort_by_score: true ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: " You are a technical expert.\n You answer questions truthfully based on provided documents.\n If the answer exists in several documents, summarize them.\n Ignore documents that don't contain the answer to the question.\n Only answer based on the documents provided. Don't make things up.\n If no information related to the question can be found in the document, say so.\n Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] .\n Never name the documents, only enter a number in square brackets as a reference.\n The reference must only refer to the number that comes in square brackets after the document.\n Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\n\n These are the documents:\n {%- if documents|length > 0 %}\n {%- for document in documents %}\n Document [{{ loop.index }}] :\n Name of Source File: {{ document.meta.file_name }}\n {{ document.content }}\n {% endfor -%}\n {%- else %}\n No relevant documents found.\n Respond with \"Sorry, no matching documents were found, please adjust the filters or try a different question.\"\n {% endif %}\n\n Question: {{ question }}\n Answer:" required_variables: variables: OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-5-mini streaming_callback: api_base_url: organization: system_prompt: generation_kwargs: timeout: max_retries: http_client_kwargs: connections: - sender: hybrid_retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: answer_builder.replies inputs: query: - "hybrid_retriever.query" - "ranker.query" - "PromptBuilder.question" - "answer_builder.query" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |--------------------|-------------------------|---------|---------------------------------------------------------------| | `query` | str | | The query string to search for. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Filters to apply during BM25 retrieval. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Filters to apply during embedding retrieval. | | `top_k` | Optional[int] | None | Maximum number of documents to return from the combined results. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|--------------------------------------------------------| | `documents` | List[Document] | | Documents retrieved and ranked using hybrid search. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-------------------------|-------------------------|------------------------|--------------------------------------------------------------------------------------------------------------------| | `document_store` | OpenSearchDocumentStore | | An instance of `OpenSearchDocumentStore` to use with the retriever. | | `embedder` | TextEmbedder | | A text embedder to embed the query for semantic search. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Default filters for BM25 retrieval. | | `fuzziness` | Union[int, str] | "AUTO" | The fuzziness setting for BM25 retrieval. | | `top_k_bm25` | int | 10 | Number of documents to return from BM25 retrieval. | | `scale_score` | bool | False | Whether to scale the BM25 scores. | | `all_terms_must_match` | bool | False | Whether all query terms must match in BM25 retrieval. | | `filter_policy_bm25` | Union[str, FilterPolicy] | "replace" | How to apply runtime filters for BM25. Options: `replace`, `merge`. | | `custom_query_bm25` | Optional[Dict[str, Any]] | None | A custom OpenSearch query for BM25 retrieval. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Default filters for embedding retrieval. | | `top_k_embedding` | int | 10 | Number of documents to return from embedding retrieval. | | `filter_policy_embedding` | Union[str, FilterPolicy] | "replace" | How to apply runtime filters for embedding retrieval. Options: `replace`, `merge`. | | `custom_query_embedding` | Optional[Dict[str, Any]] | None | A custom OpenSearch query for embedding retrieval. | | `join_mode` | Union[str, JoinMode] | "reciprocal_rank_fusion" | How to combine results from both retrievers. Options: `concatenate`, `merge`, `reciprocal_rank_fusion`, `distribution_based_rank_fusion`. | | `weights` | Optional[List[float]] | None | Weights for the joiner when combining results. | | `top_k` | Optional[int] | None | Final number of documents to return after combining results. | | `sort_by_score` | bool | True | Whether to sort the final results by score. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |---------------------|-------------------------|---------|----------------------------------------------------------------------------------------------------| | `query` | str | | The query string to search for. | | `filters_bm25` | Optional[Dict[str, Any]] | None | Filters to apply during BM25 retrieval. The way filters are applied depends on `filter_policy_bm25`. | | `filters_embedding` | Optional[Dict[str, Any]] | None | Filters to apply during embedding retrieval. The way filters are applied depends on `filter_policy_embedding`. | | `top_k` | Optional[int] | None | Maximum number of documents to return. Overrides the value set at initialization. | ## Related Information - [OpenSearchBM25Retriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchBM25Retriever.mdx) - [OpenSearchEmbeddingRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchEmbeddingRetriever.mdx) --- ## QueryExpander Generate multiple semantically similar query variations to improve retrieval recall. `QueryExpander` uses an LLM to create alternative phrasings of a query, which helps find relevant documents that might be missed with a single query formulation. ## Key Features - Generates multiple semantically similar query variations using an LLM. - Improves retrieval recall by covering different phrasings of the same question. - Works with any chat generator. - Configurable number of query expansions. - Optionally includes the original query in the output. - Returns results in a structured JSON format compatible with multi-query retrievers. ## Configuration 1. Drag the `QueryExpander` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `n_expansions` to control how many alternative queries to generate (default: 4). - Toggle `include_original_query` to include or exclude the original query in the output. 4. Go to the **Advanced** tab to configure a custom `chat_generator` or a custom `prompt_template`. ## Connections `QueryExpander` receives a `query` string from the `Input` component. It outputs a `queries` list. Connect the `queries` output to `MultiQueryTextRetriever` or `MultiQueryEmbeddingRetriever` to retrieve documents for each generated query. ## Source Code To check this component's source code, open [`query_expander.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/query/query_expander.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml query_expander: type: haystack.components.query.query_expander.QueryExpander init_parameters: n_expansions: 3 include_original_query: true chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator ``` This example shows how to perform retrieval with `QueryExpander` and `MultiQueryTextRetriever`. You can then send the retrieved documents to a `Ranker` or `DocumentJoiner` component to combine the results: ```yaml # haystack-pipeline components: query_expander: type: haystack.components.query.query_expander.QueryExpander init_parameters: n_expansions: 3 include_original_query: true chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: {} multi_query_retriever: type: haystack.components.retrievers.multi_query_text_retriever.MultiQueryTextRetriever init_parameters: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore top_k: 5 connections: - sender: query_expander.queries receiver: multi_query_retriever.queries max_runs_per_component: 100 metadata: {} inputs: query: - query_expander.query ``` ## Parameters ### Inputs | Parameter | Type | Description | | :------------- | :------------ | :--------------------------------------------------- | | `query` | str | The original query to expand. | | `n_expansions` | Optional[int] | Number of additional queries to generate. | ### Outputs | Parameter | Type | Description | | :--------- | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `queries` | List[str] | A list of semantically similar queries generated for the original query. If `include_original_query` is `True`, it includes the original query and the expanded alternatives; otherwise, only the expanded queries. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :----------------------- | :---------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `chat_generator` | Optional[ChatGenerator] | None | The chat generator to use for query expansion. If `None`, a default `OpenAIChatGenerator` with `gpt-4.1-mini` is used. | | `prompt_template` | Optional[str] | None | Custom PromptBuilder template for query expansion. The template should instruct the LLM to return a JSON response with the structure: `{"queries": ["query1", "query2", "query3"]}`. The template should include `query` and `n_expansions` variables. | | `n_expansions` | int | 4 | Number of alternative queries to generate. | | `include_original_query` | bool | True | Whether to include the original query in the output. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). Run method parameters take precedence over initialization parameters. | Parameter | Type | Default | Description | | :------------- | :------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `query` | str | | The original query to expand. | | `n_expansions` | Optional[int] | None | Number of additional queries to generate (not including the original). If `None`, uses the value from initialization. Can be zero to generate no additional queries. Must be positive. | ## Related Information - [MultiQueryTextRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiQueryTextRetriever.mdx) - [MultiQueryEmbeddingRetriever](/docs/reference/pipeline-components/knowledge-retrieval/MultiQueryEmbeddingRetriever.mdx) --- ## SentenceTransformersDocumentEmbedder(Knowledge-retrieval) Calculate document embeddings using Sentence Transformers models. Use this component in indexing pipelines to embed documents before writing them to a document store. ## Key Features - Calculates dense embeddings for documents using Sentence Transformers models. - Stores embeddings in the `embedding` metadata field of each document. - Supports embedding document metadata fields alongside document text. - Configurable batch size and progress reporting. - Supports L2 normalization for consistent embedding comparison. ## Configuration 1. Drag the `SentenceTransformersDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `model` to the Sentence Transformers model to use (for example, `sentence-transformers/all-mpnet-base-v2`). - Toggle `normalize_embeddings` to enable L2 normalization. - Set `batch_size` to control how many documents are embedded at once. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `progress_bar`, `trust_remote_code`, `token`, and `device`. :::info GPU Acceleration When using custom embedding models, enable GPU acceleration in your index settings if your index is slow: 1. Go to Indexes and click the index that contains the `SentenceTransformersDocumentEmbedder` component. You're redirected to the Index Details page. 2. Go to **Settings** and click the GPU Acceleration toggle to turn it on. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration-for-indexes). ::: ## Connections `SentenceTransformersDocumentEmbedder` receives a list of documents through its `documents` input, typically from a `DocumentSplitter` or other preprocessor. It outputs a `documents` list with the `embedding` field populated. Connect the output to `DocumentWriter` to write the embedded documents to a document store. ## Source Code To check this component's source code, open [`sentence_transformers_document_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/sentence_transformers_document_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false batch_size: 32 progress_bar: true normalize_embeddings: false embedding_separator: "\n" trust_remote_code: false ``` ### Using the Component in a Pipeline This index uses `SentenceTransformersDocumentEmbedder` to embed documents before writing them to a document store: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 document_embedder: type: haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder init_parameters: model: sentence-transformers/all-mpnet-base-v2 token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false prefix: suffix: batch_size: 32 progress_bar: true normalize_embeddings: false meta_fields_to_embed: embedding_separator: "\n" trust_remote_code: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false policy: WRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-------------|----------------|---------|---------------------| | `documents` | List[Document] | | Documents to embed. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|-------------------------------------| | `documents` | List[Document] | | Documents with embeddings populated. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------------------|----------------------------------------------------------|----------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `model` | str | sentence-transformers/all-mpnet-base-v2 | The model to use for calculating embeddings. Pass a local path or the ID of the model on Hugging Face. | | `device` | Optional[ComponentDevice] | None | The device to use for loading the model. Overrides the default device. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token to download private models from Hugging Face. | | `prefix` | str | | A string to add at the beginning of each document text. Can be used to prepend an instruction, as required by some embedding models such as E5 and bge. | | `suffix` | str | | A string to add at the end of each document text. | | `batch_size` | int | 32 | Number of documents to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when embedding documents. | | `normalize_embeddings` | bool | False | If `True`, normalizes the embeddings using L2 normalization so that each embedding has a norm of 1. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | \n | Separator used to concatenate the metadata fields to the document text. | | `trust_remote_code` | bool | False | If `False`, allows only Hugging Face verified model architectures. If `True`, allows custom models and scripts. | | `local_files_only` | bool | False | If `True`, does not attempt to download the model from Hugging Face Hub and only looks at local files. | | `truncate_dim` | Optional[int] | None | The dimension to truncate sentence embeddings to. `None` does no truncation. If the model wasn't trained with Matryoshka Representation Learning, truncating embeddings can significantly affect performance. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `precision` | Literal['float32', 'int8', 'uint8', 'binary', 'ubinary'] | float32 | The precision to use for the embeddings. All non-float32 precisions are quantized embeddings. Quantized embeddings are smaller and faster to compute, but may have lower accuracy. | | `encode_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `SentenceTransformer.encode` when embedding documents. | | `backend` | Literal['torch', 'onnx', 'openvino'] | torch | The backend to use for the Sentence Transformers model. Refer to the [Sentence Transformers documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html) for more information. | | `revision` | Optional[str] | None | The specific model version to use. It can be a branch name, a tag name, or a commit ID for a stored model on Hugging Face. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|----------------|---------|---------------------| | `documents` | List[Document] | | Documents to embed. | --- ## SentenceTransformersSparseDocumentEmbedder Calculate sparse embeddings for documents using Sentence Transformers sparse models. The model runs locally, so no external API calls are made during embedding. Use this component in indexing pipelines to add sparse embeddings to documents before writing them to a document store. ## Key Features - Calculates sparse embeddings for documents using SPLADE-based models. - Stores sparse embeddings in the `sparse_embedding` metadata field of each document. - Supports embedding document metadata fields alongside document text. - Configurable batch size and progress reporting. ## Configuration 1. Drag the `SentenceTransformersSparseDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `model` to the sparse embedding model to use (for example, `prithivida/Splade_PP_en_v2`). - Set `batch_size` to control how many documents are embedded at once. - Toggle `progress_bar` to show or hide a progress bar during embedding. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `trust_remote_code`, `token`, and `device`. ## Connections `SentenceTransformersSparseDocumentEmbedder` receives a list of documents through its `documents` input, typically from a `DocumentSplitter` or other preprocessor. It outputs a `documents` list with the `sparse_embedding` field populated. Connect the output to `DocumentWriter` to write the embedded documents to a document store. ## Source Code To check this component's source code, open [`sentence_transformers_sparse_document_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/sentence_transformers_sparse_document_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml SparseDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_sparse_document_embedder.SentenceTransformersSparseDocumentEmbedder init_parameters: model: prithivida/Splade_PP_en_v2 batch_size: 32 progress_bar: true ``` This index uses `SentenceTransformersSparseDocumentEmbedder` to create sparse embeddings for documents: ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: store_full_path: false DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en SparseDocumentEmbedder: type: haystack.components.embedders.sentence_transformers_sparse_document_embedder.SentenceTransformersSparseDocumentEmbedder init_parameters: model: prithivida/Splade_PP_en_v2 batch_size: 32 progress_bar: true DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources - sender: FileTypeRouter.application/pdf receiver: PDFMinerToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: TextFileToDocument.documents receiver: DocumentJoiner.documents - sender: PDFMinerToDocument.documents receiver: DocumentJoiner.documents - sender: MarkdownToDocument.documents receiver: DocumentJoiner.documents - sender: DocumentJoiner.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: SparseDocumentEmbedder.documents - sender: SparseDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-------------|----------------|---------|---------------------| | `documents` | List[Document] | | Documents to embed. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|---------------------------------------------------------------------------| | `documents` | List[Document] | | Documents with sparse embeddings added in the `sparse_embedding` field. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------------------|------------------------------------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `model` | str | prithivida/Splade_PP_en_v2 | The model to use for calculating sparse embeddings. Pass a local path or the ID of the model on Hugging Face. | | `device` | Optional[ComponentDevice] | None | The device to use for loading the model. Overrides the default device. | | `token` | Optional[Secret] | | The API token to download private models from Hugging Face. | | `prefix` | str | "" | A string to add at the beginning of each document text. | | `suffix` | str | "" | A string to add at the end of each document text. | | `batch_size` | int | 32 | Number of documents to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when embedding documents. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | "\n" | Separator used to concatenate the metadata fields to the document text. | | `trust_remote_code` | bool | False | If `True`, allows custom models and scripts. | | `local_files_only` | bool | False | If `True`, only looks at local files without downloading from Hugging Face Hub. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `backend` | Literal["torch", "onnx", "openvino"] | torch | The backend to use for the Sentence Transformers model. Refer to the [Sentence Transformers documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html) for more information. | | `revision` | Optional[str] | None | The specific model version to use. It can be a branch name, a tag name, or a commit ID for a stored model on Hugging Face. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|----------------|---------|---------------------| | `documents` | List[Document] | | Documents to embed. | --- ## SentenceTransformersSparseTextEmbedder Embed text strings, such as queries, using sparse embedding models from Sentence Transformers. Use this component in query pipelines to convert queries into sparse vectors for sparse embedding retrieval. ## Key Features - Generates sparse embeddings using SPLADE-based models where non-zero values represent term importance weights. - Combines the benefits of learned sparse representations with efficient sparse retrieval. - Compatible with sparse embedding retrievers. - Supports authentication for private Hugging Face models. ### Compatible Models Compatible models are based on SPLADE (SParse Lexical AnD Expansion), a technique for producing sparse representations for text. For more information, see [Pipeline Components](/docs/concepts/about-pipelines/pipeline-components.mdx). ## Configuration 1. Drag the `SentenceTransformersSparseTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `model` to the sparse embedding model to use (for example, `prithivida/Splade_PP_en_v2`). - Optionally set `prefix` or `suffix` to prepend or append text to the input before embedding. 4. Go to the **Advanced** tab to configure `token`, `trust_remote_code`, and `device`. ## Configuration 1. Drag the `SentenceTransformersSparseTextEmbedder` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name. Specify the path to a local model or the ID of the model on Hugging Face. 4. Go to the **Advanced** tab to configure `device`, `token`, `prefix`, `suffix`, `trust_remote_code`, `model_kwargs`, `tokenizer_kwargs`, `config_kwargs`, `backend`, and `revision`. ## Connections `SentenceTransformersSparseTextEmbedder` accepts a `text` string as input. It outputs `sparse_embedding` — a sparse vector representation of the input text. Typically, you connect the pipeline `Input` component to the `text` input and send `sparse_embedding` to a sparse embedding retriever. To use private models from Hugging Face, connect the platform to Hugging Face first. For details, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). ## Source Code To check this component's source code, open [`sentence_transformers_sparse_text_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/sentence_transformers_sparse_text_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Connections `SentenceTransformersSparseTextEmbedder` receives a `text` string from the `Input` component. It outputs a `sparse_embedding` that you can send to a sparse embedding retriever such as `QdrantSparseEmbeddingRetriever`. ## Usage Examples ### Basic Configuration ```yaml sparse_text_embedder: type: haystack.components.embedders.sentence_transformers_sparse_text_embedder.SentenceTransformersSparseTextEmbedder init_parameters: model: prithivida/Splade_PP_en_v2 prefix: '' suffix: '' ``` ```yaml # haystack-pipeline components: sparse_text_embedder: type: haystack.components.embedders.sentence_transformers_sparse_text_embedder.SentenceTransformersSparseTextEmbedder init_parameters: model: prithivida/Splade_PP_en_v2 # SPLADE model for sparse embeddings prefix: "" suffix: "" sparse_retriever: type: haystack_integrations.components.retrievers.qdrant.retriever.QdrantSparseEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.qdrant.document_store.QdrantDocumentStore init_parameters: location: ${QDRANT_HOST} api_key: ${QDRANT_API_KEY} index: default use_sparse_embeddings: true return_embedding: false top_k: 10 scale_score: false prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a helpful assistant. Answer the question based on the provided documents. If the documents don't contain enough information, say so. Documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: gpt-4o generation_kwargs: max_tokens: 500 temperature: 0.0 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: sparse_text_embedder.sparse_embedding receiver: sparse_retriever.query_sparse_embedding - sender: sparse_retriever.documents receiver: prompt_builder.documents - sender: sparse_retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - sparse_text_embedder.text - prompt_builder.question - answer_builder.query filters: - sparse_retriever.filters outputs: documents: sparse_retriever.documents answers: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|------------------| | `text` | str | | Text to embed. | ### Outputs | Parameter | Type | Default | Description | |------------------|-----------------|---------|-----------------------------------------| | `sparse_embedding` | SparseEmbedding | | The sparse embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |--------------------|------------------------------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `model` | str | prithivida/Splade_PP_en_v2 | The model to use for calculating sparse embeddings. Specify the path to a local model or the ID of the model on Hugging Face. For available models, check [Hugging Face](https://huggingface.co/models?search=splade). | | `device` | Optional[ComponentDevice] | None | Overrides the default device used to load the model. | | `token` | Optional[Secret] | | An API token to use private models from Hugging Face. | | `prefix` | str | "" | A string to add at the beginning of each text to embed. Some models benefit from a prefix; for example, `prithivida/Splade_PP_en_v2` may benefit from `"query: "`. | | `suffix` | str | "" | A string to add at the end of each text to embed. | | `trust_remote_code` | bool | False | If `True`, permits custom models and scripts. | | `local_files_only` | bool | False | If `True`, only looks at local files without downloading from Hugging Face Hub. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `backend` | Literal["torch", "onnx", "openvino"] | torch | The backend to use for the Sentence Transformers model. Refer to the [Sentence Transformers documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html) for more information. | | `revision` | Optional[str] | None | The specific model version to use. It can be a branch name, a tag name, or a commit ID for a stored model on Hugging Face. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|----------------| | `text` | str | | Text to embed. | --- ## SentenceTransformersTextEmbedder(Knowledge-retrieval) Embed strings, such as user queries, using Sentence Transformers models. The model runs locally, so no external API calls are made during embedding. Use this component in query pipelines to embed user queries for semantic search. ## Key Features - Embeds text strings into dense vectors using Sentence Transformers models. - Supports L2 normalization for consistent embedding comparison. - Configurable batch size for efficient processing. - Works with `OpenSearchEmbeddingRetriever` and other embedding-based retrievers. ## Configuration 1. Drag the `SentenceTransformersTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `model` to the Sentence Transformers model to use (for example, `sentence-transformers/all-mpnet-base-v2`). - Toggle `normalize_embeddings` to enable L2 normalization. - Set `batch_size` to control how many texts are embedded at once. 4. Go to the **Advanced** tab to configure `prefix`, `suffix`, `progress_bar`, `trust_remote_code`, `token`, and `device`. ## Connections `SentenceTransformersTextEmbedder` receives a `text` string, typically from the `Input` component. It outputs an `embedding` (list of floats) that you can send to an embedding-based retriever such as `OpenSearchEmbeddingRetriever`. ## Source Code To check this component's source code, open [`sentence_transformers_text_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/sentence_transformers_text_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 ``` This is a query pipeline that uses `SentenceTransformersTextEmbedder` to embed a query and retrieve documents: ```yaml # haystack-pipeline components: query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding inputs: query: - query_embedder.text - embedding_retriever.query filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|----------------| | `text` | str | | Text to embed. | ### Outputs | Parameter | Type | Default | Description | |-------------|-------------|---------|---------------------------------| | `embedding` | List[float] | | The embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------------------|----------------------------------------------------------|----------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `model` | str | sentence-transformers/all-mpnet-base-v2 | The model to use for calculating embeddings. Specify the path to a local model or the ID of the model on Hugging Face. | | `device` | Optional[ComponentDevice] | None | Overrides the default device used to load the model. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | An API token to use private models from Hugging Face. | | `prefix` | str | | A string to add at the beginning of each text to be embedded. You can use it to prepend an instruction, as required by some embedding models such as E5 and bge. | | `suffix` | str | | A string to add at the end of each text to embed. | | `batch_size` | int | 32 | Number of texts to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar for calculating embeddings. If `False`, disables the progress bar. | | `normalize_embeddings` | bool | False | If `True`, normalizes the embeddings using L2 normalization so that the embeddings have a norm of 1. | | `trust_remote_code` | bool | False | If `False`, permits only Hugging Face verified model architectures. If `True`, permits custom models and scripts. | | `local_files_only` | bool | False | If `True`, does not attempt to download the model from Hugging Face Hub and only looks at local files. | | `truncate_dim` | Optional[int] | None | The dimension to truncate sentence embeddings to. `None` does no truncation. If the model has not been trained with Matryoshka Representation Learning, truncation can significantly affect performance. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `precision` | Literal['float32', 'int8', 'uint8', 'binary', 'ubinary'] | float32 | The precision to use for the embeddings. All non-float32 precisions are quantized embeddings. Quantized embeddings are smaller and faster to compute, but may have lower accuracy. | | `encode_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `SentenceTransformer.encode` when embedding texts. | | `backend` | Literal['torch', 'onnx', 'openvino'] | torch | The backend to use for the Sentence Transformers model. Refer to the [Sentence Transformers documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html) for more information. | | `revision` | Optional[str] | None | The specific model version to use. It can be a branch name, a tag name, or a commit ID for a stored model on Hugging Face. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|----------------| | `text` | str | | Text to embed. | ## Related Information - [OpenSearchEmbeddingRetriever](/docs/reference/pipeline-components/knowledge-retrieval/OpenSearchEmbeddingRetriever.mdx) - [SentenceTransformersDocumentEmbedder](/docs/reference/pipeline-components/knowledge-retrieval/SentenceTransformersDocumentEmbedder.mdx) --- ## SentenceWindowRetriever Retrieve documents adjacent to a given document in the document store to provide fuller context. When an initial retriever finds a relevant sentence, `SentenceWindowRetriever` fetches the surrounding sentences before and after it, giving the LLM more context to work with. ## Key Features - Expands retrieval context by fetching neighboring documents around each retrieved document. - Configurable window size to control how many surrounding documents to include. - Compatible with BM25 and embedding-based retrievers. - Supports multiple document store backends (OpenSearch, Elasticsearch, Pgvector, Pinecone, Qdrant, Astra). - Flexible source document identification using single or multiple metadata fields. ## Configuration 1. Drag the `SentenceWindowRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the `document_store` to retrieve neighboring documents from. - Set `window_size` to control how many documents to fetch before and after each retrieved document (default: 3). 4. Go to the **Advanced** tab to configure `source_id_meta_field`, `split_id_meta_field`, and `raise_on_missing_meta_fields`. ## Connections `SentenceWindowRetriever` receives a list of retrieved documents through its `retrieved_documents` input, typically from a BM25 or embedding retriever. It outputs two values: `context_windows` (a list of concatenated strings) and `context_documents` (a list of document objects including context). Connect `context_documents` to a prompt builder or LLM for downstream processing. ## Source Code To check this component's source code, open [`sentence_window_retriever.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/retrievers/sentence_window_retriever.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml SentenceWindowRetriever: type: haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: Standard-Index-English window_size: 3 source_id_meta_field: source_id ``` ```yaml # haystack-pipeline components: SentenceWindowRetriever: type: haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' window_size: 3 source_id_meta_field: source_id # Can also be a list: ["source_id", "file_id"] ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------------------|----------------|---------|------------------------------------------------------------------------------------------------------------------------------------| | `retrieved_documents` | List[Document] | | List of retrieved documents from the previous retriever. | | `window_size` | Optional[int] | None | The number of documents to retrieve before and after the relevant one. Overrides the `window_size` parameter set at initialization. | ### Outputs | Parameter | Type | Default | Description | |-------------------|----------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `context_windows` | List[str] | | A list of strings, where each string represents the concatenated text from the context window of the corresponding document in `retrieved_documents`. | | `context_documents` | List[Document] | | A list of `Document` objects, containing the retrieved documents plus the context documents surrounding them. The documents are sorted by the `split_idx_start` metadata field. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |------------------------------|--------------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `document_store` | DocumentStore | | The document store to retrieve the surrounding documents from. | | `window_size` | int | 3 | The number of documents to retrieve before and after the relevant one. For example, `window_size: 2` fetches two preceding and two following documents. | | `source_id_meta_field` | Union[str, List[str]] | source_id | The metadata field containing the ID of the original document. Can be a single field name or a list of field names. When a list is provided, only documents matching all specified fields are retrieved. | | `split_id_meta_field` | str | "split_id" | The metadata field that contains the split ID of the document. | | `raise_on_missing_meta_fields` | bool | True | If `True`, raises an error if the documents do not contain the required metadata fields. If `False`, skips retrieving context for documents with missing metadata fields, but still includes the original document in the results. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------------------|----------------|---------|------------------------------------------------------------------------------------------------------------------------------------| | `retrieved_documents` | List[Document] | | List of retrieved documents from the previous retriever. | | `window_size` | Optional[int] | None | The number of documents to retrieve before and after the relevant one. Overrides the `window_size` parameter set at initialization. | --- ## SimilarDocumentsRetriever Retrieve similar documents for each document provided. The component runs a retrieval query for each input document using a preset retriever, making it useful for finding related content based on existing documents. ## Key Features - Retrieves similar documents for each document in an input list. - Runs a separate retrieval query for every document provided. - Compatible with any retriever (BM25 or embedding-based). - Supports both text-based and embedding-based retrieval modes. ## Configuration 1. Drag the `SimilarDocumentsRetriever` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the underlying `retriever` to use for finding similar documents. - Set `with_embedding` to `True` if your retriever is queried with embeddings rather than text. ## Connections `SimilarDocumentsRetriever` receives a list of documents through its `documents` input, typically from a ranker or another retriever. It outputs `document_lists` — a list of lists, where each inner list contains documents similar to the corresponding input document. ## Usage Examples ### Basic Configuration ```yaml SimilarDocumentsRetriever: type: deepset_cloud_custom_nodes.retrievers.similar_documents_retriever.SimilarDocumentsRetriever init_parameters: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: default ``` ### Using the Component in a Pipeline This query pipeline retrieves documents, then finds similar documents for each result: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default top_k: 5 similar_docs_retriever: type: deepset_cloud_custom_nodes.retrievers.similar_documents_retriever.SimilarDocumentsRetriever init_parameters: with_embedding: false retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default top_k: 3 connections: - sender: bm25_retriever.documents receiver: similar_docs_retriever.documents inputs: query: - bm25_retriever.query outputs: document_lists: similar_docs_retriever.document_lists max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-------------|----------------|---------|-------------------------------------------------------------------------------------------| | `documents` | List[Document] | | List of documents to find similar documents for. The retriever runs for every document provided. | ### Outputs | Parameter | Type | Default | Description | |------------------|----------------------|---------|-------------------------------------------------------------------------------------------| | `document_lists` | List[List[Document]] | | Retrieved documents, similar to the original document list provided to the component. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------------|-----------|---------|------------------------------------------------------------------------------------------| | `retriever` | Retriever | | Retriever to use to retrieve similar documents. | | `with_embedding` | bool | False | If `True`, assumes the retriever is queried with embeddings rather than text. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|----------------|---------|-------------------------------------------------------------------------------------------| | `documents` | List[Document] | | List of documents to find similar documents for. The retriever runs for every document provided. | --- ## TopPSampler Filter documents using top-p (nucleus) sampling based on cumulative probability scores. The component selects documents whose scores fall within the top `p` percent of the cumulative distribution, focusing on high-probability documents while filtering out less relevant ones. ## Key Features - Filters documents based on cumulative probability thresholds (nucleus sampling). - Configurable probability threshold to control how many documents are retained. - Optional minimum document count to ensure a minimum number of results. - Supports custom score metadata fields. ## Configuration 1. Drag the `TopPSampler` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `top_p` to the cumulative probability threshold (0 to 1). A value of 1.0 retains all documents. - Optionally set `score_field` to specify which metadata field contains document scores. - Optionally set `min_top_k` to ensure a minimum number of documents are returned. ## Connections `TopPSampler` accepts a list of documents through its `documents` input, typically from a retriever or ranker. It outputs a filtered `documents` list. Connect the output to an LLM or prompt builder for downstream processing. ## Source Code To check this component's source code, open [`top_p.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/samplers/top_p.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TopPSampler: type: haystack.components.samplers.top_p.TopPSampler init_parameters: {} ``` Typically, you place `TopPSampler` after a retriever or ranker that assigns scores to documents, and before a `PromptBuilder` or generator to reduce the number of documents passed to the LLM. ```yaml # haystack-pipeline components: TopPSampler: type: haystack.components.samplers.top_p.TopPSampler init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-------------|----------------|---------|-------------------------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | List of documents to filter. | | `top_p` | Optional[float] | None | If specified, overrides the cumulative probability threshold set during initialization. | ### Outputs | Parameter | Type | Default | Description | |-------------|----------------|---------|--------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | List of documents selected based on the top-p sampling. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-------------|---------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `top_p` | float | 1 | Float between 0 and 1 representing the cumulative probability threshold for document selection. A value of 1.0 means no filtering (all documents are retained). | | `score_field` | Optional[str] | None | Name of the field in each document's metadata that contains the score. If `None`, the default document score field is used. | | `min_top_k` | Optional[int] | None | If specified, the minimum number of documents to return. If the top-p sampling selects fewer documents, additional ones with the next highest scores are added to the selection. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-------------|----------------|---------|-------------------------------------------------------------------------------------------------------------------| | `documents` | List[Document] | | List of documents to filter. | | `top_p` | Optional[float] | None | If specified, overrides the cumulative probability threshold set during initialization. | --- ## Knowledge Retrieval Overview # Knowledge Retrieval Components Knowledge Retrieval components help your pipeline find the right information for a user query. Use them to turn a question into a search request, fetch the most relevant documents from your database, and prepare the results so downstream components (such as readers or LLMs) have the context they need. This group includes retrievers for different backends and strategies (for example BM25, embedding, or hybrid retrieval), embedders that create vectors for queries and documents, and utilities to improve or shape retrieval. You can also find components for query expansion, filtering, metadata filter parsing, LLM-based ranking, and ranking or grouping results based on metadata, so you can tune retrieval for quality, speed, and the structure of your data. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## AmazonBedrockChatGenerator(Legacy-components) Use chat completion models hosted on Amazon Bedrock. This component supports models from AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. With `AmazonBedrockChatGenerator`, you can use chat completion models from AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. ## Key Features - Supports chat completion models from multiple providers: AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. - Accepts a list of `ChatMessage` objects as input, making it compatible with `ChatPromptBuilder`. - Supports tool calling for agentic workflows. - Supports streaming responses token by token. - Uses AWS credentials for authentication. ## Configuration 1. Drag the `AmazonBedrockChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `amazon.nova-pro-v1:0`). 2. Configure your AWS credentials. You'll need: - **AWS Access Key ID** - **AWS Secret Access Key** - **AWS Region Name** (make sure the region supports Amazon Bedrock) - Optionally, **AWS Session Token** and **AWS Profile Name**. 4. Go to the **Advanced** tab to configure additional settings such as `generation_kwargs`, `streaming_callback`, `boto3_config`, `stop_words`, and `tools`. ## Connections `AmazonBedrockChatGenerator` receives a list of `ChatMessage` objects from `ChatPromptBuilder` through its `messages` input. It outputs a list of `ChatMessage` objects through its `replies` output. You typically connect its `replies` output to an `OutputAdapter` that converts the replies into a format that `AnswerBuilder` or `DeepsetAnswerBuilder` can accept. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/generators/amazon_bedrock/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockChatGenerator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: amazon.nova-pro-v1:0 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false ``` ### Using the Component in a Pipeline This is an example of a RAG chat pipeline with `AmazonBedrockChatGenerator`. Note that it receives instructions from `ChatPromptBuilder`, and it needs an `OutputAdapter` to send the generated replies to `DeepsetAnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm AmazonBedrockChatGenerator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: amazon.nova-pro-v1:0 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false generation_kwargs: streaming_callback: boto3_config: tools: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: AmazonBedrockChatGenerator.messages - sender: AmazonBedrockChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `messages` | List[ChatMessage] | A list of `ChatMessage` objects that form the chat history. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | A callback function to invoke when the model starts streaming responses. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments passed to the model. | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tools for the model to call. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[ChatMessage] | Responses generated by the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `model` | str | | The name of the model to use. | | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var('AWS_ACCESS_KEY_ID', strict=False) | The AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var('AWS_SECRET_ACCESS_KEY', strict=False) | The AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var('AWS_SESSION_TOKEN', strict=False) | The AWS session token. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var('AWS_DEFAULT_REGION', strict=False) | The AWS region name. Make sure the region you set supports Amazon Bedrock. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var('AWS_PROFILE', strict=False) | The AWS profile name. | | `max_length` | Optional[int] | None | The maximum length of the generated text. This can also be set in the `kwargs` parameter by using the model specific parameter name. | | `truncate` | Optional[bool] | None | Deprecated. This parameter no longer has any effect. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | | `boto3_config` | Optional[Dict[str, Any]] | None | The configuration for the boto3 client. | | `model_family` | Optional[MODEL_FAMILIES] | None | The model family to use. If not provided, the model adapter is selected based on the model name. | | `system_cachepoint_config_ttl` | `"5m"` \| `"1h"` \| None | None | Time-to-live (TTL) for the system prompt cache. Set to `"5m"` for 5 minutes, `"1h"` for 1 hour, or `None` to disable prompt caching. | | `kwargs` | Any | | Additional keyword arguments to be passed to the model. You can find the model specific arguments in AWS Bedrock's [documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt to generate a response for. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments passed to the generator. | ## Related Information - [Use Amazon Bedrock Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AmazonBedrockGenerator Generate text using models hosted on Amazon Bedrock. This component supports models from AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. With `AmazonBedrockGenerator`, you can generate text using models from AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon. The models currently supported are: - Anthropic's Claude - AI21 Labs' Jurassic-2 - Stability AI's Stable Diffusion - Cohere's Command - Meta's Llama 2 - Amazon Titan ## Key Features - Supports text generation models from multiple providers through Amazon Bedrock. - String-based input and output interface, compatible with `PromptBuilder`. - Supports streaming responses token by token. - Configurable via AWS credentials (access key ID, secret access key, region). - Model-specific arguments can be passed using the `kwargs` parameter. ## Configuration 1. Drag the `AmazonBedrockGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `anthropic.claude-3-5-sonnet-20241022-v2:0`). 2. Configure your AWS credentials. You'll need: - **AWS Access Key ID** - **AWS Secret Access Key** - **AWS Region Name** (make sure the region supports Amazon Bedrock) - Optionally, **AWS Session Token** and **AWS Profile Name**. 4. Go to the **Advanced** tab to configure additional settings such as `max_length`, `streaming_callback`, `boto3_config`, and `model_family`. ## Connections `AmazonBedrockGenerator` receives instructions and optionally documents from `PromptBuilder` through its `prompt` input. It outputs generated text as a list of strings through its `replies` output, which you typically connect to `AnswerBuilder` or `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_bedrock/src/haystack_integrations/components/generators/amazon_bedrock/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AmazonBedrockGenerator: type: haystack_integrations.components.generators.amazon_bedrock.generator.AmazonBedrockGenerator init_parameters: model: anthropic.claude-3-5-sonnet-20241022-v2:0 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false ``` This is a RAG chat pipeline that uses `AmazonBedrockGenerator`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: required_variables: "*" answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm AmazonBedrockGenerator: type: haystack_integrations.components.generators.amazon_bedrock.generator.AmazonBedrockGenerator init_parameters: model: anthropic.claude-3-5-sonnet-20241022-v2:0 aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false max_length: truncate: streaming_callback: boto3_config: model_family: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: prompt_builder.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: prompt_builder.prompt receiver: AmazonBedrockGenerator.prompt - sender: AmazonBedrockGenerator.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | A callback function to invoke when the model starts streaming responses. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments passed to the model. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | Responses generated by the model. | | `meta` | Dict[str, Any] | Metadata related to the response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `model` | str | | The name of the model to use. | | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var('AWS_ACCESS_KEY_ID', strict=False) | The AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var('AWS_SECRET_ACCESS_KEY', strict=False) | The AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var('AWS_SESSION_TOKEN', strict=False) | The AWS session token. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var('AWS_DEFAULT_REGION', strict=False) | The AWS region name. Make sure the region you set supports Amazon Bedrock. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var('AWS_PROFILE', strict=False) | The AWS profile name. | | `max_length` | Optional[int] | None | The maximum length of the generated text. This can also be set in the `kwargs` parameter by using the model specific parameter name. | | `truncate` | Optional[bool] | None | Deprecated. This parameter no longer has any effect. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. The callback function accepts StreamingChunk as an argument. | | `boto3_config` | Optional[Dict[str, Any]] | None | The configuration for the boto3 client. | | `model_family` | Optional[MODEL_FAMILIES] | None | The model family to use. If not provided, the model adapter is selected based on the model name. | | `kwargs` | Any | | Additional keyword arguments to be passed to the model. You can find the model specific arguments in AWS Bedrock's [documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt to generate a response for. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments passed to the generator. | ## Related Information - [Use Amazon Bedrock Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/using-amazon-bedrock-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AnthropicChatGenerator(Legacy-components) Use Anthropic's chat completion models to generate responses from a list of chat messages. For a list of Anthropic models you can use, see [Anthropic Models](https://docs.anthropic.com/en/docs/about-claude/models/overview). ## Key Features - Supports Anthropic's Claude family of chat completion models. - Accepts a list of `ChatMessage` objects as input, making it compatible with `ChatPromptBuilder`. - Supports tool calling for agentic workflows. - Supports streaming responses token by token. - Customizable generation via `generation_kwargs` — any parameter that works with `anthropic.Message.create` also works here. ## Configuration 1. Drag the `AnthropicChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `claude-sonnet-4-20250514`). 2. Make sure is connected to Anthropic. You'll need an Anthropic API key. For details, see [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx). 4. Go to the **Advanced** tab to configure additional settings such as `system_prompt`, `generation_kwargs`, `streaming_callback`, `timeout`, and `max_retries`. ## Connections `AnthropicChatGenerator` receives a list of `ChatMessage` objects from `ChatPromptBuilder` through its `messages` input. It outputs a list of `ChatMessage` objects through its `replies` output. You typically connect its `replies` output to an `OutputAdapter` that converts the replies into a format that `AnswerBuilder` or `DeepsetAnswerBuilder` can accept. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml anthropic_chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: model: claude-sonnet-4-20250514 generation_kwargs: temperature: 0.7 max_tokens: 500 ``` This is a RAG pipeline that uses Claude Sonnet 4: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 chat_prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: | You are a helpful assistant answering questions based on the provided documents. If the documents don't contain the answer, say so. Do not use your own knowledge. _role: system - _content: - text: | Documents: {% for document in documents %} Document [{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ query }} _role: user anthropic_chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: model: claude-sonnet-4-20250514 generation_kwargs: temperature: 0.7 max_tokens: 500 output_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: chat_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: chat_prompt_builder.prompt receiver: anthropic_chat_generator.messages - sender: anthropic_chat_generator.replies receiver: output_adapter.replies - sender: output_adapter.output receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - chat_prompt_builder.query - answer_builder.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents answers: answer_builder.answers metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `messages` | List[ChatMessage] | A list of `ChatMessage` objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for the model. | | `streaming_callback` | Optional[StreamingCallbackT] | An optional callback function to handle streaming chunks. | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tool objects or a toolset that the model can use. Each tool must have a unique name. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[ChatMessage] | A list of generated replies. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('ANTHROPIC_API_KEY') | The Anthropic API key. | | `model` | str | claude-sonnet-4-20250514 | The name of the Anthropic model to use. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | An optional callback function to handle streaming chunks. | | `system_prompt` | Optional[str] | None | An optional system prompt to use for generation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for generation. | | `timeout` | Optional[float] | None | The timeout for the request. | | `max_retries` | Optional[int] | None | The maximum number of retries if a request fails. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `messages` | List[ChatMessage] | | A list of `ChatMessage` objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for generation. For a complete list, see [Anthropic API documentation](https://docs.anthropic.com/claude/reference/messages_post). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | An optional callback function to handle streaming chunks. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tool objects or a toolset that the model can use. Each tool must have a unique name. | ## Related Information - [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## AnthropicGenerator Generate text using large language models (LLMs) by Anthropic. For a complete list of models that work with this generator, see [Anthropic documentation](https://docs.anthropic.com/en/docs/about-claude/models/overview). Although Anthropic natively supports a much richer messaging API, this component intentionally simplifies it so that the main input and output interface is string-based. For more complete support, consider using `AnthropicChatGenerator`. ## Key Features - Simplified string-based interface for text generation with Anthropic models. - Compatible with `PromptBuilder` for receiving prompts and with `DeepsetAnswerBuilder` for building answers with references. - Supports streaming responses token by token. - Customizable generation via `generation_kwargs`. - Optional system prompt for defining model behavior. ## Configuration 1. Drag the `AnthropicGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `claude-sonnet-4-20250514`). 2. Make sure is connected to Anthropic. You'll need an Anthropic API key. For details, see [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx). 4. Go to the **Advanced** tab to configure additional settings such as `system_prompt`, `generation_kwargs`, `streaming_callback`, `timeout`, and `max_retries`. ## Connections `AnthropicGenerator` receives instructions from `PromptBuilder` through its `prompt` input. It outputs generated text as a list of strings through its `replies` output, which you typically connect to `DeepsetAnswerBuilder` or `AnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml AnthropicGenerator: type: haystack_integrations.components.generators.anthropic.generator.AnthropicGenerator init_parameters: api_key: type: env_var env_vars: - ANTHROPIC_API_KEY strict: false model: claude-sonnet-4-20250514 ``` This is a RAG pipeline that uses Claude Sonnet 4: ```yaml # haystack-pipeline components: retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.open_search_hybrid_retriever.OpenSearchHybridRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/multilingual-e5-base ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: svalabs/cross-electra-ms-marco-german-uncased top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- Du bist ein technischer Experte. Du beantwortest die Fragen wahrheitsgemäß auf Grundlage der vorgelegten Dokumente. Wenn die Antwort in mehreren Dokumenten enthalten ist, fasse diese zusammen. Ignoriere Dokumente, die keine Antwort auf die Frage enthalten. Antworte nur auf der Grundlage der vorgelegten Dokumente. Erfinde keine Fakten. Wenn in dem Dokument keine Informationen zu der Frage gefunden werden können, gib dies an. Verwende immer Verweise in der Form [NUMMER DES DOKUMENTS], wenn du Informationen aus einem Dokument verwendest, z. B. [3] für Dokument [3] . Nenne die Dokumente nie, sondern gebe nur eine Zahl in eckigen Klammern als Referenz an. Der Verweis darf sich nur auf die Nummer beziehen, die in eckigen Klammern hinter der Passage steht. Andernfalls verwende in deiner Antwort keine Klammern und gib NUR die Nummer des Dokuments an, ohne das Wort Dokument zu erwähnen. Gebe eine präzise, exakte und strukturierte Antwort ohne die Frage zu wiederholen. Hier sind die Dokumente: {%- if documents|length > 0 %} {%- for document in documents %} Dokument [{{ loop.index }}] : Name der Quelldatei: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} Keine Dokumente gefunden. Sage "Es wurden leider keine passenden Dokumente gefunden, bitte passen sie die Filter an oder versuchen es mit einer veränderten Frage." {% endif %} Frage: {{ question }} Antwort: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm # extract_xml_tags: # uncomment to move thinking part into answer's meta # - thinking attachments_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate weights: top_k: sort_by_score: true AnthropicGenerator: type: haystack_integrations.components.generators.anthropic.generator.AnthropicGenerator init_parameters: api_key: type: env_var env_vars: - ANTHROPIC_API_KEY strict: false model: claude-sonnet-4-20250514 streaming_callback: system_prompt: generation_kwargs: S3Downloader: type: haystack_integrations.components.downloaders.s3.s3_downloader.S3Downloader init_parameters: aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false boto3_config: file_root_path: file_extensions: file_name_meta_key: file_name max_workers: 32 max_cache_size: 100 s3_key_generation_function: deepset_cloud_custom_nodes.utils.storage.get_s3_key connections: # Defines how the components are connected - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: meta_field_grouping_ranker.documents receiver: attachments_joiner.documents - sender: attachments_joiner.documents receiver: answer_builder.documents - sender: attachments_joiner.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: AnthropicGenerator.prompt - sender: AnthropicGenerator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: S3Downloader.documents - sender: S3Downloader.documents receiver: attachments_joiner.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "retriever.query" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "retriever.filters_bm25" - "retriever.filters_embedding" outputs: # Defines the output of your pipeline documents: "attachments_joiner.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The instructions for the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | An optional callback function to handle streaming chunks. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of generated replies. | | `meta` | List[Dict[str, Any]] | A list of metadata dictionaries for each reply. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('ANTHROPIC_API_KEY') | The Anthropic API key. | | `model` | str | claude-sonnet-4-20250514 | The name of the Anthropic model to use. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | An optional callback function to handle streaming chunks. | | `system_prompt` | Optional[str] | None | An optional system prompt to use for generation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for generation. | | `timeout` | Optional[float] | None | The timeout for the request. | | `max_retries` | Optional[int] | None | The maximum number of retries if a request fails. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt with instructions for the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for generation. For a complete list, see [Anthropic API documentation](https://docs.anthropic.com/claude/reference/messages_post). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | An optional callback function to handle streaming chunks. | ## Related Information - [Use Anthropic Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-anthropic-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## Base64ImageJoiner Join multiple lists of Base64Images into a single list. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. ::: ## Key Features - Joins multiple lists of `Base64Image` objects from different converters into a single list. - Configurable `top_k` to limit the number of images returned. - Useful in visual RAG pipelines that handle multiple file types (for example, both PDFs and images). ## Configuration 1. Drag the `Base64ImageJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, no required settings need to be configured. The component joins all images it receives. 4. Go to the **Advanced** tab to set `top_k` to limit the maximum number of images returned. ## Connections `Base64ImageJoiner` accepts multiple lists of `Base64Image` objects through its variadic `images` input. You typically connect it to converters such as `DeepsetFileToBase64Image` or `DeepsetPDFDocumentToBase64Image`. It outputs a merged `List[Base64Image]` through its `images` output, which you can connect to an `OutputAdapter` to convert the images into chat messages for a Generator. ## Usage Examples ### Basic Configuration ```yaml Base64ImageJoiner: type: deepset_cloud_custom_nodes.joiners.base64_image_joiner.Base64ImageJoiner init_parameters: {} ``` This is an example of a visual RAG chat pipeline configured to accept files uploaded in Playground. It answers questions based on images. Two converters convert files and PDFs into `Base64Image` objects. The converters then send the resulting images to `Base64ImageJoiner`, which joins them into a single list and sends them to `OutputAdapter`. `OutputAdapter` converts them into a list of chat messages with images that a Generator can process. ```yaml # haystack-pipeline # If you need help with the YAML format, have a look at https://docs.cloud.deepset.ai/v2.0/docs/create-a-pipeline#create-a-pipeline-using-pipeline-editor. # This section defines components that you want to use in your pipelines. Each component must have a name and a type. You can also set the component's parameters here. # The name is up to you, you can give your component a friendly name. You then use components' names when specifying the connections in the pipeline. # Type is the class path of the component. You can check the type on the component's documentation page. components: BM25Retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 Embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: BAAI/bge-m3 EmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 DocumentJoiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate Ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: BAAI/bge-reranker-v2-m3 top_k: 5 MetaFieldGroupingRanker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id sort_docs_by: split_id FileDownloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .pdf - .png - .jpeg - .jpg - .gif FileToBase64Image: type: deepset_cloud_custom_nodes.converters.file_to_image.DeepsetFileToBase64Image init_parameters: detail: auto PDFToBase64Image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: high missing_page_number: all_pages PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: '*' template: | Answer the questions briefly and precisely using the images and text passages provided. Only use images and text passages that are related to the question to answer it. Give reasons for your answer. In your answer, only refer to images and text passages that are relevant in answering the query. Each image is related to exactly one document. You see the images in exactly the same order as the documents. Only use references in the form [NUMBER OF IMAGE] if you are using information from an image. Or [NUMBER OF DOCUMENT] if you are using information from a document. For example, for Document [1] use the reference [1]. For Image 1 use reference [1] as well. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} Relates to image: [{{ loop.index }}] {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: LLM: type: deepset_cloud_custom_nodes.generators.openai_vision.DeepsetOpenAIVisionGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": false} model: gpt-4o generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 AnswerBuilder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: pdf: operator: OR conditions: - field: meta.mime_type operator: == value: application/pdf image: operator: OR conditions: - field: meta.mime_type operator: == value: image/png - field: meta.mime_type operator: == value: image/jpg - field: meta.mime_type operator: == value: image/jpeg - field: meta.mime_type operator: == value: image/gif RankSorter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: output_type: List[deepset_cloud_custom_nodes.dataclasses.chat_message_with_images.Base64Image] unsafe: true template: "{{ images|sort(attribute=\"meta._rank\") }}" RankAdder: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: output_type: List[haystack.Document] custom_filters: '' unsafe: true template: | {%- for document in documents -%} {%- set _ = document.meta.update({'_rank': loop.index}) -%} {%- endfor -%} {{ documents }} Base64ImageJoiner: type: deepset_cloud_custom_nodes.joiners.base64_image_joiner.Base64ImageJoiner init_parameters: {} connections: # Defines how the components are connected - sender: BM25Retriever.documents receiver: DocumentJoiner.documents - sender: EmbeddingRetriever.documents receiver: DocumentJoiner.documents - sender: PromptBuilder.prompt receiver: LLM.prompt - sender: PromptBuilder.prompt receiver: AnswerBuilder.prompt - sender: Embedder.embedding receiver: EmbeddingRetriever.query_embedding - sender: DocumentJoiner.documents receiver: Ranker.documents - sender: Ranker.documents receiver: MetaFieldGroupingRanker.documents - sender: MetaFieldGroupingRanker.documents receiver: FileDownloader.documents - sender: MetadataRouter.image receiver: FileToBase64Image.documents - sender: MetadataRouter.pdf receiver: PDFToBase64Image.documents - sender: RankSorter.output receiver: LLM.images - sender: LLM.replies receiver: AnswerBuilder.replies - sender: PDFToBase64Image.base64_images receiver: Base64ImageJoiner.images - sender: FileToBase64Image.base64_images receiver: Base64ImageJoiner.images - sender: Base64ImageJoiner.images receiver: RankSorter.images - sender: RankAdder.output receiver: MetadataRouter.documents - sender: FileDownloader.documents receiver: RankAdder.documents - sender: RankAdder.output receiver: AnswerBuilder.documents - sender: RankAdder.output receiver: PromptBuilder.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "BM25Retriever.query" - "PromptBuilder.question" - "AnswerBuilder.query" - Embedder.text - Ranker.query filters: # These components will receive a potential query filter as input - "BM25Retriever.filters" - "EmbeddingRetriever.filters" files: - FileDownloader.sources outputs: # Defines the output of your pipeline documents: "RankAdder.output" # The output of the pipeline is the retrieved documents answers: "AnswerBuilder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `images` | Variadic[List[Base64Image]] | The images to be merged. | | `top_k` | Optional[int] | The maximum number of images to return. Overrides the instance's `top_k` if provided. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `images` | List[Base64Image] | A merged list of `Base64Image` objects. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `top_k` | Optional[int] | None | The maximum number of documents to return. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `images` | Variadic[List[Base64Image]] | | The images to be merged. | | `top_k` | Optional[int] | None | The maximum number of images to return. Overrides the instance's `top_k` if provided. | --- ## ChatPromptBuilder Use `ChatPromptBuilder` to send a prompt to a `ChatGenerator`. It renders chat prompts from static or dynamic templates using the `ChatMessage` format or Jinja2 strings. `ChatPromptBuilder` renders a chat prompt from a template. It constructs prompts using static or dynamic templates, which you can update for each pipeline run. The template is a list of `ChatMessage` objects provided in the ChatMessage format or as Jinja2 strings. Template variables in the template are optional unless specified otherwise. If an optional variable isn't provided, it defaults to an empty string. Use `variable` and `required_variables` to define input types and required variables. ## Key Features - Renders chat prompts from Jinja2 templates in `ChatMessage` format. - Supports both static and dynamic templates, which you can update per pipeline run. - Supports images in prompts using the `templatize_part` filter. - Compatible with all `ChatGenerator` components. - Can receive ranked documents from a `Ranker` and include them in the prompt. ## Configuration 1. Drag the `ChatPromptBuilder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the prompt template in `ChatMessage` format. The template must include at least one message with a `_role` (`system`, `user`, `assistant`, or `tool`) and `_content`. You can use Jinja2 variables in the content. 2. Optionally, configure `required_variables` to specify which variables must be present at runtime. 4. Go to the **Advanced** tab to configure `variables` if you want to define additional input variable names beyond those inferred from the template. ### ChatMessage format `ChatMessage` is a data class that represents a message in a chat. It contains the following fields: - `role`: The role of the message. Available roles are `system`, `user`, `tool`, and `assistant`. - `content`: The content of the message. - `metadata`: The metadata of the message. In the `template` parameter, you can pass a list of `ChatMessage` objects in the following format: ```yaml - _content: - content_type: | #replace this with the content type, supported types are text, image, tool_call, and tool_call_result Type the prompt here, it may contain Jinja2 variables. _role: role # supported roles are system, user, tool, and assistant _metadata: - key: value # optional metadata ``` For example: ```yaml - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Question: {{ query }} _role: user ``` You can also pass the same content as a Jinja2 string using the `{% message %}` tag: :::info ChaMessages in Prompt Explorer Prompt Explorer only supports prompts with the `{% message %}` tag. Use the ChatMessage string format if you want to test your prompt in Prompt Explorer. ::: ```text {% message role="system" %} You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. {% endmessage %} {% message role="user" %} Question: {{ query }} {% endmessage %} ``` ## Connections `ChatPromptBuilder` receives pipeline variables (such as `query` and `documents`) through its dynamic `**kwargs` input. It outputs a rendered list of `ChatMessage` objects through its `prompt` output, which you connect to a `ChatGenerator`'s `messages` input. You can also connect a `Ranker`'s `documents` output to `ChatPromptBuilder` to include retrieved documents in the prompt. ## Source Code To check this component's source code, open [`chat_prompt_builder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/builders/chat_prompt_builder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system ``` ### Initializing the Component ```yaml # haystack-pipeline components: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system ``` ### Using the Component in a Pipeline #### Using the ChatMessage Format `ChatPromptBuilder` sends the instructions to a `ChatGenerator` in the form of a list of `ChatMessage` objects. You pass the instructions in the `template` parameter, which must follow the `ChatMessage` format: For example: ```jinja2 - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Question: {{ query }} _role: user ``` You can also pass documents in the prompt, like this: ```jinja2 - _content: - text: | Here are the results that your last search yielded. {% for doc in documents %} {{doc.content}} {% endfor %} Question: {{ query }} _role: user ``` `ChatPromptBuilder` also supports passing images in prompts using the `templatize_part` filter: ```jinja2 - _content: - text: | What's the difference between the following images? {% for image in images %} {{ image | templatize_part }} {% endfor %} {% endmessage %} _role: user ``` #### Using the Jinja2 Template Syntax You can use Jinja2 strings in ChatPromptBuilder's template parameter through the `{% message %}` tag. This makes it possible to create structured ChatMessages with mixed content types, such as images and text. For example, this ChatPromptBuilder contains instructions for follow up question classification and rewriting queries at the start of the pipeline. There are two chat messages, one with role "system" and another one with role "assistant". It also includes chat history. ```yaml # haystack-pipeline components: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: | {% message role="system" %} You are an excellent labeling tool. You receive a chat history. If the last user question is asking for information from a database, output "QUESTION". This is also the case when something needs to be explained. If the last user question contains instructions for working with a given passage, output "PASSAGE". If the chat history is empty, the label "PASSAGE" cannot be used. Example questions referring to the passage are: "write a summary of this", "in bullet points", or "rephrase as an email". For the "QUESTION" label, you additionally output a "query". The "query" must be in natural language, since it will be processed by a hybrid of keyword and semantic search. Therefore, be as explicit as possible with the keywords. If both X and Y are asked about, only include Y in the "query" and do not repeat X. Abbreviations such as "ArbVG", "BVwG", or "Abs", as well as all paragraphs, must remain unchanged and must not be reformulated in the "query". If the question does not need context from the chat history, output it unchanged in the "query". For the "PASSAGE" label, you output NOTHING additional. Simply: "PASSAGE". {% endmessage %} {% for message in chat_history %} {% message role=message.role %} {{ message.text }} {% endmessage %} {% endfor %} {% message role="assistant" %} {% endmessage %} ``` ### ChatMessage `ChatMessage` is a data class that represents a message in a chat. It contains the following fields: - `role`: The role of the message. Available roles are `system`, `user`, `tool`,and `assistant`. - `content`: The content of the message. - `metadata`: The metadata of the message. In the `template` parameter, you can pass a list of `ChatMessage` objects in the following format: ```yaml - _content: - content_type: | #replace this with the content type, supported types are text, image, tool_call, and tool_call_result Type the prompt here, it may contain Jinja2 variables. _role: role # supported roles are system, user, tool, and assistant _metadata: - key: value # optional metadata ``` For example: ```yaml - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Question: {{ query }} _role: user ``` You can also pass the same content as a Jinja2 string using the `{% message %}` tag: :::info ChaMessages in Prompt Explorer Prompt Explorer only supports prompts with the `{% message %}` tag. Use the ChatMessage string format if you want to test your prompt in Prompt Explorer. ::: ```text {% message role="system" %} You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. {% endmessage %} {% message role="user" %} Question: {{ query }} {% endmessage %} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `template` | Optional[List[ChatMessage]] | An optional list of `ChatMessage` objects to send to the LLM. | | `template_variables` | Optional[Dict[str, Any]] | An optional dictionary of variables to include in the template. | | `kwargs` | Any | Pipeline variables used for rendering the prompt. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | List[ChatMessage] | The updated list of `ChatMessage` objects after rendering the templates. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `template` | Optional[List[ChatMessage]] | None | A list of `ChatMessage` objects. The component looks for Jinja2 template syntax and renders the prompt with the provided variables. | | `required_variables` | Optional[Union[List[str], Literal['*']]] | None | A list of variables that `ChatPromptBuilder` must receive as input. If a variable listed as required is not provided, an exception is raised. If set to `"*"`, all variables in the prompt are required. | | `variables` | Optional[List[str]] | None | A list of input variables to use in prompt templates instead of the ones inferred from the `template` parameter. For example, to use more variables during prompt engineering than the ones present in the default template, you can provide them here. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `template` | Optional[List[ChatMessage]] | None | An optional list of `ChatMessage` objects to overwrite `ChatPromptBuilder`'s default template. If `None`, the default template provided at initialization is used. | | `template_variables` | Optional[Dict[str, Any]] | None | An optional dictionary of template variables to overwrite the pipeline variables. | | `kwargs` | Any | | Pipeline variables used for rendering the prompt. | --- ## DeepsetAmazonBedrockChatGenerator Generate chat responses using Amazon Bedrock models with integration. `DeepsetAmazonBedrockChatGenerator` generates chat responses using Amazon Bedrock models hosted on 's Bedrock account. This component provides access to various foundation models available through Amazon Bedrock, including Claude, Llama, and Titan models. ## Key Features - Accesses Amazon Bedrock models through 's account — no separate AWS account required. - Supports chat completion interface with `ChatMessage` input and output. - Supports tool calling for agentic workflows. - Supports streaming responses token by token. - Configurable generation parameters such as `max_tokens`, `temperature`, and `top_p`. ## Configuration 1. Drag the `DeepsetAmazonBedrockChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the Amazon Bedrock model identifier in the **Model** field (for example, `anthropic.claude-3-sonnet-20240229-v1:0`). 2. Set the AWS region name where the Bedrock service is accessed. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `streaming_callback`, `boto3_config`, and `tools`. ## Connections `DeepsetAmazonBedrockChatGenerator` receives a list of `ChatMessage` objects from `ChatPromptBuilder` through its `messages` input. It outputs a list of `ChatMessage` objects through its `replies` output, which you connect to `AnswerBuilder` or `DeepsetAnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml generator: type: deepset_cloud_custom_nodes.generators.chat.deepset_amazon_bedrock_chat_generator.DeepsetAmazonBedrockChatGenerator init_parameters: model: anthropic.claude-3-sonnet-20240229-v1:0 aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false generation_kwargs: max_tokens: 1000 temperature: 0.7 ``` This is an example RAG pipeline using `DeepsetAmazonBedrockChatGenerator` with Amazon Bedrock models: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _role: system _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents. Do not use your own knowledge." - _role: user _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" variables: required_variables: generator: type: deepset_cloud_custom_nodes.generators.chat.deepset_amazon_bedrock_chat_generator.DeepsetAmazonBedrockChatGenerator init_parameters: model: anthropic.claude-3-sonnet-20240229-v1:0 aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false generation_kwargs: max_tokens: 1000 temperature: 0.7 streaming_callback: boto3_config: tools: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: generator.messages - sender: generator.replies receiver: answer_builder.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `messages` | List[ChatMessage] | A list of chat messages to send to the model. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[ChatMessage] | Generated chat message responses from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `model` | str | | The Amazon Bedrock model identifier to use for generation. | | `aws_region_name` | Optional[str] | None | AWS region name where the Bedrock service is accessed. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional parameters for generation, such as `max_tokens`, `temperature`, `top_p`. | | `streaming_callback` | Optional[Callable] | None | A callback function called when a new token is received during streaming. | | `boto3_config` | Optional[Dict[str, Any]] | None | Configuration for the boto3 client. | | `tools` | Optional[List[Tool]] | None | A list of tools the model can use for function calling. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `messages` | List[ChatMessage] | | A list of chat messages to send to the model. | --- ## DeepsetAmazonBedrockGenerator Generate text using large language models hosted on 's Amazon Bedrock account, so you don't need to create your own account. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. You can replace it with the `AmazonBedrockChatGenerator` component. ::: `DeepsetAmazonBedrockGenerator` makes it possible to use models in [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) through 's Bedrock account. You don't need your own Bedrock account to use these models. To use models through your own Bedrock account, use `AmazonBedrockGenerator`. For a full list of models, see [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html). ## Key Features - Accesses Amazon Bedrock models through 's account — no separate AWS account required. - String-based input and output interface, compatible with `PromptBuilder`. - Supports streaming responses token by token. - Configurable region, max length, and model-specific parameters. ## Configuration 1. Drag the `DeepsetAmazonBedrockGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `meta.llama2-13b-chat-v1`). 2. Set the AWS region name. Supported regions are: - `us-east-1`: Works for most models. - `us-west-2`: Choose for newest models. - `eu-central-1`: Choose for EU-hosted models. 4. Go to the **Advanced** tab to configure `max_length`, `streaming_callback`, and other model-specific `kwargs`. ## Connections `DeepsetAmazonBedrockGenerator` receives the prompt from `PromptBuilder` through its `prompt` input. It outputs generated text as a list of strings through its `replies` output, which you connect to `AnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml DeepsetAmazonBedrockGenerator: type: deepset_cloud_custom_nodes.generators.deepset_amazon_bedrock_generator.DeepsetAmazonBedrockGenerator init_parameters: model: amazon.titan-text-premier-v1:0 ``` This example uses the Llama2 model hosted on Amazon Bedrock to generate answers. It gets the prompt with documents from `PromptBuilder` and then sends the generated replies to `AnswerBuilder`: ```yaml # haystack-pipeline components: # ... prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: llm: type: deepset_cloud_custom_nodes.generators.deepset_amazon_bedrock_generator.DeepsetAmazonBedrockGenerator init_parameters: model: "meta.llama2-13b-chat-v1" aws_region_name: us-east-1 # Region name is required max_length: 400 model_max_length: 4096 temperature: 0 streaming_callback: deepset_cloud_custom_nodes.callbacks.streaming.streaming_callback # makes this generator stream answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder connections: # ... - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters potentially override the parameters passed in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `model` | str | | The name or path of the model in Amazon Bedrock. | | `aws_region_name` | str \| None | None | The AWS region. Supported regions: `us-east-1` (works for most models), `us-west-2` (newest models), `eu-central-1` (EU-hosted models). | | `max_length` | int \| None | 100 | The maximum length of generated text. | | `truncate` | bool \| None | True | Whether to truncate the generated text to the maximum length. | | `streaming_callback` | Callable[[StreamingChunk], None] \| None | None | A callback function to handle streaming chunks. | | `kwargs` | Any | | Additional keyword arguments for the model. These arguments are model-specific. For supported arguments, check the model's documentation. | ### Run Method Parameters This component doesn't accept any runtime parameters. --- ## DeepsetAmazonBedrockVisionGenerator Generate text using prompts containing text and images with large language models hosted on Amazon Bedrock. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. You can replace it with the `AmazonBedrockChatGenerator` component. ::: `DeepsetAmazonBedrockVisionGenerator` makes it possible to use models in [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) through 's Amazon Bedrock account. This component only works with models that support multimodal inputs. For a full list of models, see [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html). ## Key Features - Accepts both text prompts and images (as `Base64Image` objects) for multimodal generation. - Accesses Amazon Bedrock models through 's account — no separate AWS account required. - Supports streaming responses token by token. - Any text generation parameters valid for the underlying model can be passed via `generation_kwargs`. ## Configuration 1. Drag the `DeepsetAmazonBedrockVisionGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `anthropic.claude-3-5-sonnet-20241022-v2:0`). 2. Optionally, enter a system prompt to define the model's behavior. 4. Go to the **Advanced** tab to configure `streaming_callback` and `generation_kwargs`. ## Connections `DeepsetAmazonBedrockVisionGenerator` receives a text prompt from `PromptBuilder` through its `prompt` input and a list of `Base64Image` objects (typically from `DeepsetPDFDocumentToBase64Image`) through its `images` input. It outputs generated text as a list of strings through its `replies` output, which you connect to `DeepsetAnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml DeepsetAmazonBedrockVisionGenerator: type: deepset_cloud_custom_nodes.generators.deepset_amazon_bedrock_vision_generator.DeepsetAmazonBedrockVisionGenerator init_parameters: model: anthropic.claude-3-5-sonnet-20241022-v2:0 ``` This example uses the Sonnet 3.5 model hosted on Amazon Bedrock to generate answers. It gets the prompt with documents from `PromptBuilder` and then sends the generated replies to `AnswerBuilder`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 1024 top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: "BAAI/bge-m3" embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 1024 top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: "BAAI/bge-reranker-v2-m3" top_k: 5 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: null sort_docs_by: split_id image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - ".pdf" pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: "high" prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the question briefly and precisely based on the pictures. Give reasons for your answer. When answering the question only provide references within the answer text. Only use references in the form [NUMBER OF IMAGE] if you are using information from a image. For example, if the first image is used in the answer add [1] and if the second image is used then use [2], etc. Never name the images, but always enter a number in square brackets as a reference. Question: {{ question }} Answer: required_variables: "*" llm: type: deepset_cloud_custom_nodes.generators.deepset_amazon_bedrock_vision_generator.DeepsetAmazonBedrockVisionGenerator init_parameters: model: anthropic.claude-3-5-sonnet-20241022-v2:0 aws_region_name: us-west-2 max_length: 10000 model_max_length: 200000 temperature: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: image_downloader.documents - sender: image_downloader.documents receiver: pdf_to_image.documents - sender: pdf_to_image.base64_images receiver: llm.images - sender: prompt_builder.prompt receiver: llm.prompt - sender: image_downloader.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: llm.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "pdf_to_image.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `images` | List[Base64Image] | A list of Base64Images that represent the image content of the message. The base64 encoded images are passed to the large language model for text generation. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | A callback function to handle streaming chunks. To learn more about streaming, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters potentially override the parameters passed in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `model` | str | | The model to use for text generation. | | `system_prompt` | Optional[str] | None | A system prompt to use for role prompting. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. To learn more, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt for the model. | | `images` | List[Base64Image] | | A list of Base64Images that represent the image content of the message. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function to handle streaming chunks. To learn more, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters potentially override the parameters in pipeline configuration. | --- ## DeepsetAzureOpenAIVisionGenerator Generate text using text and image capabilities of OpenAI's LLMs through Azure services. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. You can replace it with the AzureOpenAIChatGenerator` component. ::: `DeepsetAzureOpenAIVisionGenerator` works with GPT-4 and GPT-3.5 turbo families of models hosted on Azure. These models can understand images, making it possible to describe them, analyze details, and answer questions based on images. For details and limitations, check [OpenAI's Vision](https://platform.openai.com/docs/guides/vision) documentation. ## Key Features - Accepts both text prompts and images (as `Base64Image` objects) for multimodal generation. - Works with GPT-4 and GPT-3.5 turbo families of models hosted on Azure. - Supports streaming responses token by token. - Customizable generation via `generation_kwargs`, including `max_tokens`, `temperature`, `top_p`, and more. ## Configuration 1. Drag the `DeepsetAzureOpenAIVisionGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the **Azure Endpoint** (for example, `https://example-resource.azure.openai.com/`). 2. Enter the **Azure Deployment** name (usually the model name, for example, `gpt-4o`). 3. Enter the **API Version** (for example, `2023-05-15`). 4. Make sure is connected to Azure OpenAI. You need an Azure OpenAI API key and endpoint. For help, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). 4. Go to the **Advanced** tab to configure `system_prompt`, `streaming_callback`, `generation_kwargs`, `timeout`, `max_retries`, and `default_headers`. ## Connections `DeepsetAzureOpenAIVisionGenerator` receives a text prompt from `PromptBuilder` through its `prompt` input and a list of `Base64Image` objects (typically from `DeepsetPDFDocumentToBase64Image`) through its `images` input. It outputs generated text as a list of strings through its `replies` output, which you connect to `DeepsetAnswerBuilder`. Here's an example of the pipeline in Pipeline Builder: ## Usage Examples ### Basic Configuration ```yaml DeepsetAzureOpenAIVisionGenerator: type: deepset_cloud_custom_nodes.generators.azure_openai_vision.DeepsetAzureOpenAIVisionGenerator init_parameters: azure_endpoint: api_version: '2023-05-15' azure_deployment: gpt-4o generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 ``` ### Using the Component in a Pipeline Here's an example of a query pipeline with `DeepsetAzureOpenAIVisionGenerator`. It's preceded by `DeepsetFileDownloader` (`image_downloader`), which downloads the documents returned by previous components, such as a Ranker or `DocumentJoiner`. It then sends the downloaded files to `DeepsetPDFDocumentToBase64Image` (`pdf_to_image`), which converts them into `Base64Image` objects that `DeepsetAzureOpenAIVisionGenerator` can take in. The Generator also receives the prompt from the `PromptBuilder`. It then sends the generated replies to `DeepsetAnswerBuilder`. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: BAAI/bge-m3 tokenizer_kwargs: model_max_length: 1024 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: BAAI/bge-reranker-v2-m3 top_k: 8 model_kwargs: torch_dtype: torch.float16 tokenizer_kwargs: model_max_length: 1024 meta_fields_to_embed: - file_name image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .pdf pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: high prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the questions briefly and precisely using the images and text passages provided. Only use images and text passages that are related to the question to answer it. In your answer, only refer to images and text passages that are relevant in answering the query. Only use references in the form [NUMBER OF IMAGE] if you are using information from an image. Or [NUMBER OF DOCUMENT] if you are using information from a document. These are the documents: {% for document in documents %} Document[ {{ loop.index }} ]: File Name: {{ document.meta['file_name'] }} Text only version of image number {{ loop.index }} that is also provided. {{ document.content }} {% endfor %} Question: {{ question }} Answer: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm TopKDocuments: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: top_k: 8 DeepsetAzureOpenAIVisionGenerator: type: deepset_cloud_custom_nodes.generators.azure_openai_vision.DeepsetAzureOpenAIVisionGenerator init_parameters: azure_endpoint: api_version: '2023-05-15' azure_deployment: gpt-4o generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: image_downloader.documents receiver: pdf_to_image.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: ranker.documents receiver: prompt_builder.documents - sender: ranker.documents receiver: TopKDocuments.documents - sender: TopKDocuments.documents receiver: image_downloader.documents - sender: ranker.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: DeepsetAzureOpenAIVisionGenerator.prompt - sender: pdf_to_image.base64_images receiver: DeepsetAzureOpenAIVisionGenerator.images - sender: DeepsetAzureOpenAIVisionGenerator.replies receiver: answer_builder.replies max_loops_allowed: 100 metadata: {} inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - prompt_builder.question - answer_builder.query filters: - embedding_retriever.filters - bm25_retriever.filters outputs: answers: answer_builder.answers documents: ranker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `images` | List[Base64Image] | A list of Base64Images that represent the image content of the message. The base64 encoded images are passed to OpenAI for text generation. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters potentially override the parameters in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | | `meta` | List[Dict[str, Any]] | A list of dictionaries containing the metadata for each response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `azure_endpoint` | Optional[str] | None | The endpoint of the deployed model, for example `https://example-resource.azure.openai.com/`. | | `api_version` | Optional[str] | 2023-05-15 | The version of the API to use. | | `azure_deployment` | Optional[str] | gpt-4o | The deployment of the model, usually the model name. | | `api_key` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_API_KEY', strict=False) | The API key to use for authentication. | | `azure_ad_token` | Optional[Secret] | Secret.from_env_var('AZURE_OPENAI_AD_TOKEN', strict=False) | [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id). | | `organization` | Optional[str] | None | Your organization ID. For help, see [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function called when a new token is received from the stream. | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If not provided, the Generator omits the system prompt and uses the default system prompt. | | `timeout` | Optional[float] | None | Timeout for AzureOpenAI client. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30. | | `max_retries` | Optional[int] | None | Maximum retries to establish contact with AzureOpenAI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the OpenAI endpoint. For details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). | | `default_headers` | Optional[Dict[str, str]] | None | Default headers to use for the AzureOpenAI client. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt with instructions for the model. | | `images` | List[Base64Image] | | A list of `Base64Image`'s that represent the image content of the message. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. For more details, refer to the OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat/create). | ## Related Information - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## DeepsetChatHistoryParser Parse a string containing chat history and a current question into a list of `ChatMessage` objects. `DeepsetChatHistoryParser` is primarily used with an `Agent` to supply both the chat history and the current query. It expects input in the following format: `"Chat History: [{...array of messages...}] Current Question: {question text}"`. Each message in the chat history should be a dictionary containing two keys: `role` and `content`. If the input doesn't match this structure, `DeepsetChatHistoryParser` returns it as a single message from the user. ## Key Features - Parses a combined chat history and current query string into a list of `ChatMessage` objects. - Compatible with the `Agent` component for multi-turn conversational pipelines. - Handles malformed input gracefully by returning it as a single user message. - Requires no initialization parameters. ## Configuration 1. Drag the `DeepsetChatHistoryParser` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. This component has no required configuration. It takes no initialization parameters. ## Connections `DeepsetChatHistoryParser` receives a combined string of chat history and the current query through its `history_and_query` input — typically from the pipeline's `query` input. It outputs a list of `ChatMessage` objects through its `messages` output, which you connect to the `Agent`'s `messages` input. ## Usage Examples ### Basic Configuration ```yaml history_parser: type: deepset_cloud_custom_nodes.parsers.chat_history_parser.DeepsetChatHistoryParser init_parameters: {} ``` This is an example of an agentic pipeline with `DeepsetChatHistoryParser` used to provide the current query and chat history to the Agent: ```yaml # haystack-pipeline components: adapter: init_parameters: custom_filters: {} output_type: typing.List[str] template: '{{ [(messages|last).text] }}' unsafe: false type: haystack.components.converters.output_adapter.OutputAdapter agent: init_parameters: chat_generator: init_parameters: api_base_url: api_key: env_vars: - OPENAI_API_KEY strict: false type: env_var generation_kwargs: {} max_retries: model: gpt-4o organization: streaming_callback: timeout: tools: tools_strict: false type: haystack.components.generators.chat.openai.OpenAIChatGenerator exit_conditions: - text max_agent_steps: 100 raise_on_tool_invocation_failure: false state_schema: {} streaming_callback: system_prompt: |- You are a deep research assistant. You create comprehensive research reports to answer the user's questions. You use the 'search'-tool to answer any questions. You perform multiple searches until you have the information you need to answer the question. Make sure you research different aspects of the question. Use markdown to format your response. When you use information from the websearch results, cite your sources using markdown links. It is important that you cite accurately. tools: - data: component: init_parameters: input_mapping: query: - search.query output_mapping: builder.prompt: result pipeline: components: builder: init_parameters: required_variables: template: |- {% for doc in docs %} {% if doc.content and doc.meta.url|length > 0 %} {{ doc.content|truncate(25000) }} {% endif %} {% endfor %} variables: type: haystack.components.builders.prompt_builder.PromptBuilder converter: init_parameters: extraction_kwargs: {} store_full_path: false type: haystack.components.converters.html.HTMLToDocument fetcher: init_parameters: raise_on_failure: false retry_attempts: 2 timeout: 3 user_agents: - haystack/LinkContentFetcher/2.11.1 type: haystack.components.fetchers.link_content.LinkContentFetcher search: init_parameters: api_key: env_vars: - SERPERDEV_API_KEY strict: false type: env_var search_params: {} top_k: 10 type: haystack.components.websearch.serper_dev.SerperDevWebSearch connection_type_validation: true connections: - receiver: fetcher.urls sender: search.links - receiver: converter.sources sender: fetcher.streams - receiver: builder.docs sender: converter.documents max_runs_per_component: 100 metadata: {} type: haystack.core.super_component.super_component.SuperComponent description: Use this tool to search for information on the internet. inputs_from_state: name: search parameters: type: haystack.tools.component_tool.ComponentTool type: haystack.components.agents.agent.Agent answer_builder: init_parameters: pattern: reference_pattern: type: haystack.components.builders.answer_builder.AnswerBuilder history_parser: init_parameters: {} type: deepset_cloud_custom_nodes.parsers.chat_history_parser.DeepsetChatHistoryParser connections: - receiver: agent.messages sender: history_parser.messages - receiver: adapter.messages sender: agent.messages - receiver: answer_builder.replies sender: adapter.output inputs: query: - answer_builder.query - history_parser.history_and_query outputs: answers: answer_builder.answers pipeline_output_type: chat max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `history_and_query` | str | Chat history and the current question to convert into a list of `ChatMessage` objects. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `messages` | List[ChatMessage] | A list of `ChatMessage` objects. Each message has a role (either user or assistant) and content. | ### Init Parameters This component doesn't take any initialization parameters. ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `history_and_query` | str | | Chat history and the current query to be parsed into ChatMessages. | --- ## DeepsetFileDownloader Download files referenced by documents to the local filesystem. Use this component in visual question answering pipelines to fetch PDFs and images before conversion. :::warning Deprecation Notice This component is deprecated. Use `S3Downloader` from the Haystack AWS integration instead. Existing pipelines that use this component continue to work for now. ::: ## Key Features - Downloads files associated with documents from platform storage to local disk. - Filters downloads by file extension. - Caches downloaded files locally with a configurable cache size. - Returns updated documents with `file_path` set in metadata. - Supports concurrent downloads for multiple files. ## Configuration 1. Drag the `DeepsetFileDownloader` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Set `file_extensions` to limit which file types are downloaded. 4. Configure `sources_target_type` and `max_cache_size` as needed. :::info Warm-up required This component requires a warm-up step before it can download files. The platform handles this automatically when the pipeline runs. ::: ## Connections `DeepsetFileDownloader` accepts `documents` or `sources` as input. It outputs `documents` with `file_path` metadata and `sources` in the configured target type. Connect a Ranker or retriever that returns documents with `file_id` metadata to the input. Connect the `documents` or `sources` output to `DeepsetPDFDocumentToBase64Image`, `DeepsetFileToBase64Image`, or a visual Generator. ## Usage Examples ### Basic Configuration ```yaml DeepsetFileDownloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .pdf sources_target_type: str max_cache_size: 100 ``` ### Using the Component in a Pipeline This example downloads PDF files before converting them to images: ```yaml # haystack-pipeline components: image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .pdf sources_target_type: str max_cache_size: 100 pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: auto connections: - sender: image_downloader.documents receiver: pdf_to_image.documents ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | Optional[List[Document]] | None | Documents with `file_id` in metadata to download. | | sources | Optional[List[Union[ByteStream, UUID, str]]] | None | File IDs or byte streams to download. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | List[Document] | | Documents with `file_path` set in metadata. | | sources | List[Union[str, Path, ByteStream]] | | Downloaded file paths or byte streams in the configured target type. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | file_extensions | Optional[List[str]] | None | File extensions to download, such as `[".pdf", ".png"]`. If `None`, all file types are downloaded. | | sources_target_type | Literal["str", "pathlib.Path", "haystack.dataclasses.ByteStream"] | str | Type of the sources returned in the output. | | max_cache_size | int | 100 | Maximum number of files to keep in the local cache. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | Optional[List[Document]] | None | Documents with `file_id` in metadata to download. | | sources | Optional[List[Union[ByteStream, UUID, str]]] | None | File IDs or byte streams to download. | --- ## DeepsetFileToBase64Image Convert image files from disk into base64-encoded images for use in visual question answering pipelines. :::warning Deprecation Notice This component is deprecated. Use `ImageFileToImageContent` from Haystack instead. Existing pipelines that use this component continue to work for now. ::: ## Key Features - Reads image files from local disk and converts them to `Base64Image` objects. - Supports PNG, JPG, JPEG, and GIF file formats. - Accepts documents with `file_path` metadata or direct file sources. - Configurable image detail level for vision model input sizing. ## Configuration 1. Drag the `DeepsetFileToBase64Image` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Set `detail` to control how the image is resized before encoding. ## Connections `DeepsetFileToBase64Image` accepts `documents` with `file_path` metadata or direct `sources` as input. It outputs `documents` and `base64_images`. Connect `DeepsetFileDownloader` to provide documents with local file paths. Connect the `base64_images` output to a visual Generator such as `DeepsetOpenAIVisionGenerator` or `Base64ImageJoiner`. ## Usage Examples ### Basic Configuration ```yaml DeepsetFileToBase64Image: type: deepset_cloud_custom_nodes.converters.file_to_image.DeepsetFileToBase64Image init_parameters: detail: auto ``` ### Using the Component in a Pipeline This example converts downloaded image files to base64 for a vision Generator: ```yaml # haystack-pipeline components: image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .png - .jpg - .jpeg sources_target_type: str max_cache_size: 100 file_to_image: type: deepset_cloud_custom_nodes.converters.file_to_image.DeepsetFileToBase64Image init_parameters: detail: auto connections: - sender: image_downloader.documents receiver: file_to_image.documents ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | Optional[List[Document]] | None | Documents with `file_path` in metadata pointing to image files. | | sources | Optional[List[Union[str, Path, ByteStream]]] | None | Direct file paths or byte streams to convert. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | List[Document] | | Documents that had convertible image files. | | base64_images | List[Base64Image] | | Base64-encoded images ready for vision Generators. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | detail | Literal["auto", "low", "high"] | auto | Controls how the image is resized before encoding. See the [OpenAI vision documentation](https://platform.openai.com/docs/guides/vision) for details. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | Optional[List[Document]] | None | Documents with `file_path` in metadata. | | sources | Optional[List[Union[str, Path, ByteStream]]] | None | Direct file paths or byte streams to convert. | --- ## DeepsetMetadataGrouper Reorder documents by grouping them on metadata fields. Use this component to keep related document chunks together before sending them to an LLM. :::warning Deprecation Notice This component is deprecated. Use `MetaFieldGroupingRanker` from Haystack instead. Existing pipelines that use this component continue to work for now. ::: ## Key Features - Groups documents by a metadata field such as `file_id`. - Creates subgroups within each group using a second metadata field. - Sorts documents within groups by a numeric metadata value. - Helps LLMs process related chunks in a logical order. ## Configuration 1. Drag the `DeepsetMetadataGrouper` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Set `group_by` to the primary metadata field for grouping. 4. Optionally set `subgroup_by` and `sort_docs_by`. ## Connections `DeepsetMetadataGrouper` accepts a list of `documents` as input. It outputs `documents` — the same documents reordered by group and subgroup. Connect a `Ranker` or retriever to the input. Connect the output to a `PromptBuilder` or pipeline output. ## Usage Examples ### Basic Configuration ```yaml DeepsetMetadataGrouper: type: deepset_cloud_custom_nodes.rankers.deepset_metadata_grouper.DeepsetMetadataGrouper init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id ``` ### Using the Component in a Pipeline This example groups ranked documents by `file_id` and sorts them by `split_id`: ```yaml # haystack-pipeline components: ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: cross-encoder/ms-marco-MiniLM-L-6-v2 top_k: 15 metadata_grouper: type: deepset_cloud_custom_nodes.rankers.deepset_metadata_grouper.DeepsetMetadataGrouper init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id connections: - sender: ranker.documents receiver: metadata_grouper.documents outputs: documents: metadata_grouper.documents ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | List[Document] | | Documents to group and reorder. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | List[Document] | | Documents reordered by group and subgroup. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | group_by | str | | Metadata key used to group documents. | | subgroup_by | Optional[str] | None | Metadata key used to create subgroups within each group. | | sort_docs_by | Optional[str] | None | Metadata key used to sort documents within each group or subgroup. Documents without this key are placed at the end. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | documents | List[Document] | | Documents to group and reorder. | --- ## DeepsetOpenAIVisionGenerator Generate text using text and image capabilities of OpenAI's LLMs. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. You can replace it with the `OpenAIChatGenerator` component. ::: `DeepsetOpenAIVisionGenerator` works with the GPT families of models hosted on Azure. These models can understand images, making it possible to describe them, analyze details, and answer questions based on images. For details and limitations, check [OpenAI's Vision](https://platform.openai.com/docs/guides/vision) documentation. ## Key Features - Accepts both text prompts and images (as `Base64Image` objects) for multimodal generation. - Works with GPT-4 and other vision-capable OpenAI models. - Supports streaming responses token by token. - Customizable generation via `generation_kwargs`, including `max_tokens`, `temperature`, `top_p`, and more. ## Configuration 1. Drag the `DeepsetOpenAIVisionGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `gpt-4o`). 2. Make sure is connected to OpenAI. You need an OpenAI API key. For help, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). 4. Go to the **Advanced** tab to configure `system_prompt`, `api_base_url`, `organization`, `streaming_callback`, `generation_kwargs`, `timeout`, and `max_retries`. ## Connections `DeepsetOpenAIVisionGenerator` receives a text prompt from `PromptBuilder` through its `prompt` input and a list of `Base64Image` objects (typically from `DeepsetPDFDocumentToBase64Image`) through its `images` input. It outputs generated text as a list of strings through its `replies` output, which you connect to `DeepsetAnswerBuilder`. Here's an example of the pipeline in Pipeline Builder: ## Usage Examples ### Basic Configuration ```yaml DeepsetOpenAIVisionGenerator: type: deepset_cloud_custom_nodes.generators.openai_vision.DeepsetOpenAIVisionGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o ``` ### Using the Component in a Pipeline Here's an example of a query pipeline with `DeepsetOpenAIVisionGenerator`. It's preceded by `DeepsetFileDownloader` ("image_downloader"), which downloads the documents returned by previous components, such as a Ranker or `DocumentJoiner`. It then sends the downloaded files to `DeepsetPDFDocumentToBase64Image` ("pdf_to_image"), which converts them into `Base64Image` objects that `DeepsetOpenAIVisionGenerator` can take in. The Generator also receives the prompt from the `PromptBuilder`. It then sends the generated replies to `DeepsetAnswerBuilder`. ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: BAAI/bge-m3 tokenizer_kwargs: model_max_length: 1024 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: true verify_certs: false hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} embedding_dim: 1024 similarity: cosine index: '' max_chunk_bytes: 104857600 return_embedding: false method: mappings: settings: create_index: true timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: BAAI/bge-reranker-v2-m3 top_k: 8 model_kwargs: torch_dtype: torch.float16 tokenizer_kwargs: model_max_length: 1024 meta_fields_to_embed: - file_name image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - .pdf pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: high prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the questions briefly and precisely using the images and text passages provided. Only use images and text passages that are related to the question to answer it. In your answer, only refer to images and text passages that are relevant in answering the query. Only use references in the form [NUMBER OF IMAGE] if you are using information from an image. Or [NUMBER OF DOCUMENT] if you are using information from a document. These are the documents: {% for document in documents %} Document[ {{ loop.index }} ]: File Name: {{ document.meta['file_name'] }} Text only version of image number {{ loop.index }} that is also provided. {{ document.content }} {% endfor %} Question: {{ question }} Answer: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm TopKDocuments: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: top_k: 8 DeepsetOpenAIVisionGenerator: type: deepset_cloud_custom_nodes.generators.openai_vision.DeepsetOpenAIVisionGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o streaming_callback: api_base_url: organization: system_prompt: generation_kwargs: timeout: max_retries: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: image_downloader.documents receiver: pdf_to_image.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: ranker.documents receiver: prompt_builder.documents - sender: ranker.documents receiver: TopKDocuments.documents - sender: TopKDocuments.documents receiver: image_downloader.documents - sender: ranker.documents receiver: answer_builder.documents - sender: DeepsetOpenAIVisionGenerator.replies receiver: answer_builder.replies - sender: prompt_builder.prompt receiver: DeepsetOpenAIVisionGenerator.prompt - sender: pdf_to_image.base64_images receiver: DeepsetOpenAIVisionGenerator.images metadata: {} inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - prompt_builder.question - answer_builder.query filters: - embedding_retriever.filters - bm25_retriever.filters outputs: answers: answer_builder.answers documents: ranker.documents max_runs_per_component: 100 ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `images` | List[Base64Image] | A list of Base64Images that represent the image content of the message. The base64 encoded images are passed to OpenAI for text generation. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters potentially override the parameters in pipeline configuration. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | A callback function called when a new token is received from the stream. For more information, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | | `meta` | List[Dict[str, Any]] | A list of dictionaries containing the metadata for each response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | The OpenAI API key. | | `model` | str | gpt-4o | The name of the model to use. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function called when a new token is received from the stream. For details, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | | `api_base_url` | Optional[str] | None | An optional base URL. | | `organization` | Optional[str] | None | The Organization ID. See [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If not provided, the system prompt is omitted, and the default system prompt of the model is used. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model. These parameters are all sent directly to the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat) for more details. | | `timeout` | Optional[float] | None | Timeout for OpenAI Client calls. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30. | | `max_retries` | Optional[int] | None | Maximum retries to establish contact with OpenAI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt with instructions for the model. | | `images` | List[Base64Image] | | A list of Base64Images that represent the image content of the message. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. For more details, refer to the OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat/create). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function called when a new token is received from the stream. For more information, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | ## Related Information - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## DeepsetPDFDocumentToBase64Image # DeepsetPDFToBase64Image Convert documents sources from PDF files to base64-encoded images. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines. You can replace it with the `PDFToImageContent` component. ::: `DeepsetPDFDocumentToBase64Image` is a converter used in visual question answering pipelines to extract images from downloaded PDFs. These images are then sent to a visual Generator that can process them. It converts documents accompanied by metadata containing the `file_path` and the `page_number` pointing to the location of the image. Converting documents doesn't happen if: - The `file_path` doesn't exist in the metadata. - The `page_number` doesn't exist in the metadata. - The file path doesn't start with the expected root path. - The file path doesn't end with `.pdf`. ## Key Features - Converts PDF documents to base64-encoded images for use in visual question answering pipelines. - Outputs both text documents and corresponding `Base64Image` objects. - Configurable detail level (`auto`, `low`, or `high`) for image processing. - Handles missing page numbers with the `missing_page_number` parameter. ## Configuration 1. Drag the `DeepsetPDFDocumentToBase64Image` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Detail** level: `auto` (default), `low`, or `high`. Choose `high` for best results or `low` for lowest inference costs. 4. Go to the **Advanced** tab to configure `missing_page_number` to control how documents without a `page_number` in their metadata are handled. ## Connections `DeepsetPDFDocumentToBase64Image` receives a list of `Document` objects from `DeepsetFileDownloader` through its `documents` input. It outputs both a list of text documents through its `documents` output and a list of `Base64Image` objects through its `base64_images` output. You typically connect its `base64_images` output to a visual Generator such as `DeepsetAzureOpenAIVisionGenerator`. This is how you connect the components in Builder: ## Usage Examples ### Basic Configuration ```yaml pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: high ``` ### Using the Component in a Pipeline This component is used in our visual question answering templates, where it receives documents from `DeepsetFileDownloader` and sends them to `DeepsetAzureOpenAIVisionGenerator`. Here's the complete pipeline YAML: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - ${OPENSEARCH_HOST} http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 1024 similarity: cosine top_k: 20 # The number of results to return query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: "BAAI/bge-m3" tokenizer_kwargs: model_max_length: 1024 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: use_ssl: True verify_certs: False hosts: - ${OPENSEARCH_HOST} http_auth: - "${OPENSEARCH_USER}" - "${OPENSEARCH_PASSWORD}" embedding_dim: 1024 similarity: cosine top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: "BAAI/bge-reranker-v2-m3" top_k: 5 model_kwargs: torch_dtype: "torch.float16" tokenizer_kwargs: model_max_length: 1024 image_downloader: type: deepset_cloud_custom_nodes.augmenters.deepset_file_downloader.DeepsetFileDownloader init_parameters: file_extensions: - ".pdf" pdf_to_image: type: deepset_cloud_custom_nodes.converters.pdf_to_image.DeepsetPDFDocumentToBase64Image init_parameters: detail: "high" prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Answer the question briefly and precisely based on the pictures. Give reasons for your answer. When answering the question only provide references within the answer text. Only use references in the form [NUMBER OF IMAGE] if you are using information from a image. For example, if the first image is used in the answer add [1] and if the second image is used then use [2], etc. Never name the images, but always enter a number in square brackets as a reference. Question: {{ question }} Answer: llm: type: deepset_cloud_custom_nodes.generators.openai_vision.DeepsetOpenAIVisionGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-4o" generation_kwargs: max_tokens: 650 temperature: 0.0 seed: 0 answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: image_downloader.documents - sender: image_downloader.documents receiver: pdf_to_image.documents - sender: pdf_to_image.base64_images receiver: llm.images - sender: prompt_builder.prompt receiver: llm.prompt - sender: image_downloader.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: llm.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "pdf_to_image.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `documents` | List[Document] | A list of documents with image information in their metadata. The expected metadata is: `meta = {"file_path": str, "page_number": int}`. If this metadata is not present, the document is skipped and the component shows a warning. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `documents` | List[Document] | A list of text documents. | | `base64_images` | List[Base64Image] | A list of base64 encoded images corresponding to the documents they were converted from. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `detail` | Literal['auto', 'low', 'high'] | auto | Controls how the model processes the image and generates its textual understanding. See [OpenAI documentation](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding). | | `missing_page_number` | Literal['skip', 'all_pages'] | skip | Controls how to handle documents that do not have a `page_number` in their metadata. `skip` skips such documents. `all_pages` extracts images from all pages of the PDF if the `page_number` is not present. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `documents` | List[Document] | | A list of documents with image information in their metadata. The expected metadata is: `meta = {"file_path": str, "page_number": int}`. If this metadata is not present, the document is skipped and the component shows a warning. | --- ## DeepsetRegexParser Extract text from a string or chat message using a regular expression pattern. :::warning Deprecation Notice This component is deprecated. Use `RegexTextExtractor` from Haystack instead. Existing pipelines that use this component continue to work for now. ::: ## Key Features - Extracts text using a regex pattern with capture groups. - Accepts plain strings or lists of `ChatMessage` objects as input. - Can search all messages or only the last message in a chat history. - Supports returning a single match or all matches. ## Configuration 1. Drag the `DeepsetRegexParser` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Enter the `regex_pattern` with at least one capture group to extract the desired text. 4. Configure `consider_all_messages`, `return_all_matches`, and `return_empty_on_no_match` as needed. ## Connections `DeepsetRegexParser` accepts `text_or_messages` as input — either a string or a list of chat messages. It outputs `captured_text` for a single match or `captured_texts` for multiple matches. Connect a Generator or chat component to the input. Connect the output to components that need the extracted value, such as `DeepsetGitHubIssueViewer`. ## Usage Examples ### Basic Configuration ```yaml DeepsetRegexParser: type: deepset_cloud_custom_nodes.parsers.regex_parser.DeepsetRegexParser init_parameters: regex_pattern: '' consider_all_messages: false return_empty_on_no_match: false return_all_matches: false ``` ### Using the Component in a Pipeline This example extracts a URL from a chat message: ```yaml # haystack-pipeline components: regex_parser: type: deepset_cloud_custom_nodes.parsers.regex_parser.DeepsetRegexParser init_parameters: regex_pattern: '' consider_all_messages: false return_empty_on_no_match: false return_all_matches: false inputs: text_or_messages: - regex_parser.text_or_messages outputs: captured_text: regex_parser.captured_text ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | text_or_messages | str or List[ChatMessage] | | Text or chat messages to search. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | captured_text | str | | First captured text when `return_all_matches` is `False`. | | captured_texts | List[str] | | All captured texts when `return_all_matches` is `True`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | regex_pattern | str | | Regular expression pattern with a capture group to extract text. | | consider_all_messages | bool | False | If `True`, applies the regex to all chat messages. If `False`, only the last message is searched. | | return_empty_on_no_match | bool | False | If `True`, returns an empty dictionary when no match is found. | | return_all_matches | bool | False | If `True`, returns all matches as `captured_texts`. If `False`, returns only the first match as `captured_text`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | text_or_messages | str or List[ChatMessage] | | Text or chat messages to search. | --- ## DeepsetSourceToBase64Image Convert file sources directly to base64-encoded images. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. ::: ## Key Features - Converts file sources (such as image files) directly to base64-encoded `Base64Image` objects. - Configurable detail level (`auto`, `low`, or `high`) for image processing. - Used in visual question answering pipelines to prepare images for vision-capable generators. ## Configuration 1. Drag the `DeepsetSourceToBase64Image` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, configure the **Detail** level: `auto` (default), `low`, or `high`. 4. Go to the **Advanced** tab to configure additional settings. ## Connections `DeepsetSourceToBase64Image` receives file sources through its input and outputs a list of `Base64Image` objects. You typically connect its output to a vision-capable Generator or to `Base64ImageJoiner` when combining images from multiple sources. ## Usage Examples ### Basic Configuration ```yaml DeepsetSourceToBase64Image: type: deepset_cloud_custom_nodes.converters.file_to_image.DeepsetSourceToBase64Image init_parameters: {} ``` ### Using the Component in a Pipeline This example converts uploaded image files to base64 for a vision pipeline: ```yaml # haystack-pipeline components: source_to_image: type: deepset_cloud_custom_nodes.converters.file_to_image.DeepsetSourceToBase64Image init_parameters: detail: auto inputs: sources: - source_to_image.sources outputs: base64_images: source_to_image.base64_images max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `sources` | List[Union[str, Path, ByteStream]] | A list of file sources to convert to base64-encoded images. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `base64_images` | List[Base64Image] | A list of base64-encoded images. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `detail` | Literal['auto', 'low', 'high'] | auto | Controls how the model processes the image and generates its textual understanding. Choose `high` for best results and `low` for lowest inference costs. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sources` | List[Union[str, Path, ByteStream]] | | A list of file sources to convert to base64-encoded images. | --- ## DeepsetTogetherAIGenerator Generate text using large language models hosted on Together AI. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines for now. You can replace it with the `TogetherAIChatGenerator` component. ::: `DeepsetTogetherAIGenerator` generates answers to queries using models hosted on Together AI. For a complete list of models you can use, check [Together AI documentation](https://docs.together.ai/docs/serverless-models). ## Key Features - Supports a wide range of open-source models hosted on Together AI. - String-based input and output interface, compatible with `PromptBuilder`. - Supports streaming responses token by token. - Supports system prompts at both initialization time and run time. - Customizable generation via `generation_kwargs`, including `max_tokens`, `temperature`, and more. ## Configuration 1. Drag the `DeepsetTogetherAIGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the model name in the **Model** field (for example, `deepseek-ai/DeepSeek-R1`). 2. Make sure is connected to Together AI. You'll need a Together AI API key. For details, see [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx). 4. Go to the **Advanced** tab to configure `system_prompt`, `streaming_callback`, `api_base_url`, `generation_kwargs`, `timeout`, and `max_retries`. ## Connections `DeepsetTogetherAIGenerator` receives the prompt from `PromptBuilder` through its `prompt` input. It outputs generated text as a list of strings through its `replies` output, which you connect to `DeepsetAnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml DeepsetTogetherAIGenerator: type: deepset_cloud_custom_nodes.generators.togetherai.DeepsetTogetherAIGenerator init_parameters: model: deepseek-ai/DeepSeek-R1 api_key: type: env_var env_vars: - TOGETHERAI_API_KEY strict: false ``` ### Using the Component in a Pipeline This query pipeline uses the DeepSeek-R1 model hosted on Together AI: ```yaml # haystack-pipeline components: # ... prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: llm: type: haystack_integrations.components.generators.togetherai.generator.TogetherAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["TOGETHERAI_API_KEY"], "strict": false} model: deepseek-ai/DeepSeek-R1 generation_kwargs: max_tokens: 650 temperature: 0 seed: 0 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder connections: # ... - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt with instructions for the model. | | `system_prompt` | Optional[str] | The system prompt to use for text generation. If omitted, the system prompt defined at initialization time is used. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | A callback function called when a new token is received from the stream. For more information, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters potentially override the parameters in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | | `meta` | List[Dict[str, Any]] | A list of dictionaries containing the metadata for each response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('TOGETHERAI_API_KEY') | The together.ai API key to connect. | | `model` | str | deepseek-ai/DeepSeek-R1 | The name of the model to use. | | `api_base_url` | Optional[str] | None | The base URL of the together.ai API. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function called when a new token is received from the stream. For more information, see [Enable Streaming](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-streaming.mdx). | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If not provided, the system prompt is omitted, and the default system prompt of the model is used. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the together.ai endpoint. See together.ai [documentation](https://docs.together.ai/reference/chat-completions-1) for more details. | | `timeout` | Optional[float] | None | Timeout for together.ai Client calls. If not set, it is inferred from the `TOGETHERAI_TIMEOUT` environment variable or set to 30. | | `max_retries` | Optional[int] | None | Maximum retries to establish contact with together.ai if it returns an internal error. If not set, it is inferred from the `TOGETHER_MAX_RETRIES` environment variable or set to 5. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt with instructions for the model. | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If omitted, the system prompt defined at initialization time is used. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. For more details, refer to the together.ai [documentation](https://docs.together.ai/reference/chat-completions-1). | ## Related Information - [Use Together AI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-togetherai-models.mdx) - [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx) --- ## DeepsetVLMPDFToDocumentConverter Convert PDF documents to text using a Vision Language Model (VLM). :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines. You can replace it with the `LLMDocumentContentExtractor` component. ::: `DeepsetVLMPDFToDocumentConverter` uses a vision language model (VLM) to convert a screenshot of each PDF page into text based on your prompt. Use this converter with PDF files that have: - complex layouts - a mix of images and text - tables - handwritten text - figures Through prompting, you can convert tables, images, or figures into a textual representation which can be useful for retrieval or for passing the resulting text to an LLM. It helps to extract text in a natural reading order from PDF documents with complex layouts without having to implement custom post-processing code to keep a natural reading order. :::info Costs This component can cause high costs with OpenAI or Amazon Bedrock if you use it to convert thousands of PDF pages. For OpenAI, one PDF page equals roughly 1,500 input tokens and a page equals roughly between 800 and 3,000 output tokens. ::: ## Configuration ## Key Features - Uses a VLM to accurately convert complex PDF layouts, including tables, images, figures, and handwritten text. - Supports OpenAI models via the OpenAI API and Anthropic models via Amazon Bedrock. - Processes PDFs in parallel across files and pages for efficiency. - Fully customizable through prompt configuration. - Configurable detail level for image processing. - Supports retry logic with exponential backoff. ## Configuration 1. Drag the `DeepsetVLMPDFToDocumentConverter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Select the **VLM Provider**: `openai` or `bedrock`. 2. Enter the **Model** name (for example, `gpt-4o`). 3. Edit the **Prompt** to control how the VLM extracts content. 4. Go to the **Advanced** tab to configure `max_workers_files`, `max_workers_pages`, `max_retries`, `backoff_factor`, `initial_backoff_time`, `detail`, `generator_kwargs`, `response_extraction_pattern`, `max_splits_per_page`, `progress_bar`, and `page_separator`. ## Connections `DeepsetVLMPDFToDocumentConverter` receives PDF sources from `FileTypeRouter` through its `sources` input. It outputs converted documents through its `documents` output, which you typically connect to `DocumentJoiner` or a preprocessor for further processing. ## Usage Examples ### Basic Configuration ```yaml DeepsetVLMPDFToDocumentConverter: type: deepset_cloud_custom_nodes.converters.vlm_pdf_to_document.DeepsetVLMPDFToDocumentConverter init_parameters: vlm_provider: openai max_workers_files: 3 max_workers_pages: 5 max_retries: 3 backoff_factor: 2 initial_backoff_time: 30 prompt: |- Extract the content from the document below. You need to extract the content exactly. Format everything as markdown. Make sure to retain the reading order of the document. **Headers- and Footers** Remove repeating page headers or footers that disrupt the reading order. Place letter heads that appear at the side of a document at the top of the page. **Images** Do not extract images, drawings or maps. Instead, add a caption that describes briefly what you see on the image. Enclose each image caption with [img-caption][/img-caption] **Tables** Make sure to format the table in markdown. Add a short caption below the table that describes the table's content. Enclose each table caption with [table-caption][/table-caption]. The caption must be placed below the extracted table. **Forms** Reproduce checkbox selections with markdown. Go ahead and extract! Document: model: gpt-4o max_splits_per_page: 3 detail: auto generator_kwargs: generation_kwargs: temperature: 0 seed: 0 max_tokens: 4000 timeout: 120 progress_bar: true page_separator: "\f" ``` This is an example index, where `DeepsetVLMPDFToDocumentConverter` receives PDFs from `FileTypeRouter` and then sends the converted files to `DocumentJoiner`: ```yaml components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 markdown_converter: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: {} html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: extraction_kwargs: output_format: txt target_language: null include_tables: true include_links: false docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: {} pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.XLSXToDocument init_parameters: {} joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 1024 similarity: cosine policy: OVERWRITE DeepsetVLMPDFToDocumentConverter: type: deepset_cloud_custom_nodes.converters.vlm_pdf_to_document.DeepsetVLMPDFToDocumentConverter init_parameters: vlm_provider: openai max_workers_files: 3 max_workers_pages: 5 max_retries: 3 backoff_factor: 2 initial_backoff_time: 30 prompt: |- Extract the content from the document below. You need to extract the content exactly. Format everything as markdown. Make sure to retain the reading order of the document. **Headers- and Footers** Remove repeating page headers or footers that disrupt the reading order. Place letter heads that appear at the side of a document at the top of the page. **Images** Do not extract images, drawings or maps. Instead, add a caption that describes briefly what you see on the image. Enclose each image caption with [img-caption][/img-caption] **Tables** Make sure to format the table in markdown. Add a short caption below the table that describes the table's content. Enclose each table caption with [table-caption][/table-caption]. The caption must be placed below the extracted table. **Forms** Reproduce checkbox selections with markdown. Go ahead and extract! Document: model: gpt-4o max_splits_per_page: 3 detail: auto generator_kwargs: generation_kwargs: temperature: 0 seed: 0 max_tokens: 4000 timeout: 120 response_extraction_pattern: null progress_bar: true page_separator: "\f" connections: - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: xlsx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: writer.documents - sender: file_classifier.application/pdf receiver: DeepsetVLMPDFToDocumentConverter.sources - sender: DeepsetVLMPDFToDocumentConverter.documents receiver: joiner.documents max_runs_per_component: 100 metadata: {} inputs: files: - file_classifier.sources ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `sources` | List[Union[str, Path, ByteStream]] | List of PDF sources to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Optional metadata or list of metadata dictionaries. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `documents` | List[Document] | A list of converted documents. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `vlm_provider` | Literal['openai', 'bedrock'] | openai | Type of VLM provider to use (`openai` or `bedrock`). | | `max_workers_files` | int | 3 | Maximum number of threads for processing files. | | `max_workers_pages` | int | 5 | Maximum number of threads for processing pages. | | `max_retries` | int | 3 | Maximum number of retries for page-level extraction. | | `backoff_factor` | float | 2.0 | Factor for exponential backoff between retries. | | `initial_backoff_time` | float | 30.0 | Initial backoff time in seconds. | | `prompt` | str | Extract the content from this document page. Format everything as markdown to recreate the layout as best as possible. Retain the natural reading order. | Prompt to use for the VLM. | | `openai_api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | OpenAI API key. | | `model` | str | gpt-4o | Model name to use with the generator. | | `max_splits_per_page` | int | 3 | Maximum number of splits per page. Only applies when using `openai` as `llm_provider`. | | `detail` | Literal['auto', 'high', 'low'] | auto | Detail level for image processing. Choose `high` for the best results and `low` for the lowest inference costs. | | `generator_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for the generator. Check the Generator's documentation to learn about the parameters that you can pass. | | `response_extraction_pattern` | Optional[str] | None | Regex pattern to extract text from the generator's response. | | `progress_bar` | bool | True | Whether to display a progress bar. | | `page_separator` | str | \x0c | What string to use to separate pages. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sources` | List[Union[str, Path, ByteStream]] | | List of PDF sources to convert. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata or list of metadata dictionaries. | --- ## DocumentWriter Write documents to a DocumentStore. `DocumentWriter` is used in indexing pipelines to persist processed documents into a DocumentStore so they can be retrieved later by query pipelines. ## Key Features - Writes documents to any compatible `DocumentStore`. - Configurable duplicate handling: `NONE`, `SKIP`, `OVERWRITE`, or `FAIL`. - Returns the number of documents successfully written. ## Configuration 1. Drag the `DocumentWriter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Configure the `document_store` to specify where the documents should be written. 2. Set the `policy` to control how duplicate documents are handled. 4. Go to the **Advanced** tab if you need to override the policy at run time. ## Connections `DocumentWriter` receives a list of `Document` objects through its `documents` input — typically from a preprocessor, splitter, or embedder at the end of an indexing pipeline. It outputs the count of written documents through its `documents_written` output. `DocumentWriter` is usually the last component in an indexing pipeline. ## Source Code To check this component's source code, open [`document_writer.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/writers/document_writer.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: {} ``` ```yaml # haystack-pipeline components: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `documents` | List[Document] | A list of documents to write to the document store. | | `policy` | Optional[DuplicatePolicy] | The policy to use when encountering duplicate documents. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `documents_written` | int | Number of documents written to the document store. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `document_store` | DocumentStore | | The instance of the document store where you want to store your documents. | | `policy` | DuplicatePolicy | DuplicatePolicy.NONE | The policy to apply when a Document with the same ID already exists in the DocumentStore. `DuplicatePolicy.NONE`: Default policy, relies on the DocumentStore settings. `DuplicatePolicy.SKIP`: Skips documents with the same ID. `DuplicatePolicy.OVERWRITE`: Overwrites documents with the same ID. `DuplicatePolicy.FAIL`: Raises an error if a Document with the same ID is already in the DocumentStore. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `documents` | List[Document] | | A list of documents to write to the document store. | | `policy` | Optional[DuplicatePolicy] | None | The policy to use when encountering duplicate documents. | --- ## ExternalGenerator Call an external service with a prompt and return its response. `ExternalGenerator` sends a prompt to an external service and returns the results from the service. It expects the service to respond with `answer: str, meta: Dict`. It acts just like any other Generator except that instead of calling an LLM, it calls an external service. `ExternalGenerator` is flexible regarding what constitutes a prompt and what the external service does with it. For example, this component can send a SQL query as a prompt to be run on a database in an external service. ## Key Features - Sends a text prompt to any external HTTP service and returns the response. - Compatible with `PromptBuilder` for receiving prompts and with `DeepsetAnswerBuilder` for building answers with references. - Configurable timeout for requests. - Flexible: works with any service that accepts a string prompt and returns a string answer. ## Configuration 1. Drag the `ExternalGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: 1. Enter the **URL** of the external service to post the prompt to. 4. Go to the **Advanced** tab to configure the `timeout` for requests (default: 50 seconds). ## Connections `ExternalGenerator` receives the prompt from `PromptBuilder` through its `prompt` input. It outputs the responses from the service as a list of strings through its `replies` output, which you connect to `DeepsetAnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml ExternalGenerator: type: deepset_cloud_custom_nodes.generators.external.ExternalGenerator init_parameters: url: https://your-service.example.com/generate ``` ### Using the Component in a Pipeline This query pipeline sends a prompt to an external HTTP service and builds an answer from the response: ```yaml # haystack-pipeline components: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Answer the question: {{ query }}" required_variables: - query external_generator: type: deepset_cloud_custom_nodes.generators.external.ExternalGenerator init_parameters: url: https://your-service.example.com/generate timeout: 50 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: prompt_builder.prompt receiver: external_generator.prompt - sender: external_generator.replies receiver: answer_builder.replies inputs: query: - prompt_builder.query - answer_builder.query outputs: answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The prompt to pass to the service. | | `meta` | Optional[Dict] | Additional metadata related to the prompt. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | The answers from the service. | | `meta` | List[Dict[str, Any]] | Metadata related to the answers. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `url` | str | | The URL of the external service to post the prompt to. | | `timeout` | int | 50 | The timeout for requests sent to the URL. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The prompt to pass to the service. | | `meta` | Optional[Dict] | None | Additional metadata related to the prompt. | --- ## FallbackChatGenerator Use `FallbackChatGenerator` to try multiple chat generators sequentially. If one generator fails, it falls back to the next one in the list. If all generators fail, it raises an error with all the details. ## Key Features - Tries multiple chat generators in order and returns the first successful result. - Automatically triggers failover on any exception, including timeout, rate limit, authentication, context length, and server errors. - Forwards all parameters transparently to the underlying chat generators. - Returns detailed error information if all generators fail. - Lets you control per-generator timeout through each generator's `timeout` init parameter. ## Configuration 1. Drag the `FallbackChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Add a list of chat generators to try in order under `chat_generators`. The component tries each one in sequence until one succeeds. To control the timeout of each generator, set the `timeout` parameter in that generator's init parameters in the YAML. ## Connections `FallbackChatGenerator` accepts a list of `ChatMessage` objects as input. Connect it to any component that produces `messages`, such as `ChatPromptBuilder`. It outputs `replies` as a list of `ChatMessage` objects from the first successful generator. Connect its `replies` output to any component that consumes replies, such as `DeepsetAnswerBuilder` or `OutputAdapter`. ## Source Code To check this component's source code, open [`fallback.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/fallback.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml FallbackChatGenerator: type: haystack.components.generators.chat.fallback.FallbackChatGenerator init_parameters: chat_generators: - type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o generation_kwargs: temperature: 0.7 max_tokens: 500 - type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o-mini generation_kwargs: temperature: 0.7 max_tokens: 500 ``` This query pipeline uses `FallbackChatGenerator` to try GPT-4o first and fall back to GPT-4o-mini if it fails: ```yaml # haystack-pipeline components: ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant that answers questions concisely." _role: system - _content: - text: "Question: {{ question }}" _role: user required_variables: variables: FallbackChatGenerator: type: haystack.components.generators.chat.fallback.FallbackChatGenerator init_parameters: chat_generators: - type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o generation_kwargs: temperature: 0.7 max_tokens: 500 - type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o-mini generation_kwargs: temperature: 0.7 max_tokens: 500 AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: ChatPromptBuilder.prompt receiver: FallbackChatGenerator.messages - sender: FallbackChatGenerator.replies receiver: AnswerBuilder.replies inputs: query: - ChatPromptBuilder.question - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | The conversation history as a list of `ChatMessage` objects. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional parameters for the chat generator (for example, temperature, max_tokens). | | `tools` | Optional[ToolsType] | None | A list of Tool or Toolset objects the generator can use. | | `streaming_callback` | Optional[StreamingCallbackT] | None | Optional callable for handling streaming responses. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[ChatMessage] | | Generated `ChatMessage` objects from the first successful generator. | | `meta` | Dict[str, Any] | | Execution metadata including `successful_chat_generator_index`, `successful_chat_generator_class`, `total_attempts`, `failed_chat_generators`, and any metadata from the successful generator. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `chat_generators` | List[ChatGenerator] | | A list of chat generator components to try in order. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | The conversation history as a list of `ChatMessage` objects. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional parameters for the chat generator. | | `tools` | Optional[ToolsType] | None | A list of Tool and/or Toolset objects for the generators to use. | | `streaming_callback` | Optional[StreamingCallbackT] | None | Optional callable for handling streaming responses. | --- ## FastembedDocumentEmbedder(Legacy-components) Compute document embeddings using Fastembed embedding models. ## Key Features - Uses [Fastembed](https://qdrant.github.io/fastembed/), a lightweight, fast Python library for embedding generation. - Stores the computed embedding in the `embedding` field of each document. - Supports most state-of-the-art embedding models. - Configurable batch size and parallel processing for large datasets. - Supports embedding metadata fields alongside document content. ## Configuration 1. Drag the `FastembedDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the embedding model. You can find supported models in the [FastEmbed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/#supported-text-embedding-models). 4. Go to the **Advanced** tab to configure additional settings such as `batch_size`, `parallel`, `meta_fields_to_embed`, and `embedding_separator`. ## Connections `FastembedDocumentEmbedder` receives a list of `documents` from converters or `DocumentSplitter` in an indexing pipeline. It outputs the same documents with their `embedding` field populated. Connect its output to `DocumentWriter` to store embedded documents in a document store. ## Source Code To check this component's source code, open [`fastembed_document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `FastembedDocumentEmbedder` accepts a list of documents as input. In an indexing pipeline, connect it to converters such as `TextFileToDocument` or preprocessors such as `DocumentSplitter`. It outputs a list of documents with the `embedding` field populated. Connect its `documents` output to `DocumentWriter` to store the embedded documents in a document store. ## Usage Examples ### Basic Configuration ```yaml FastembedDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 prefix: '' suffix: '' batch_size: 256 progress_bar: true local_files_only: false embedding_separator: "\n" ``` This index uses `FastembedDocumentEmbedder` to embed documents before storing them: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 FastembedDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_document_embedder.FastembedDocumentEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 cache_dir: threads: prefix: "" suffix: "" batch_size: 256 progress_bar: true parallel: local_files_only: false meta_fields_to_embed: embedding_separator: "\n" DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: FastembedDocumentEmbedder.documents - sender: FastembedDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents to embed. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents with each Document's `embedding` field set to the computed embeddings. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | BAAI/bge-small-en-v1.5 | Local path or name of the model in Hugging Face's model hub, such as `BAAI/bge-small-en-v1.5`. | | `cache_dir` | Optional[str] | None | The path to the cache directory. Can be set using the `FASTEMBED_CACHE_PATH` env variable. Defaults to `fastembed_cache` in the system's temp directory. | | `threads` | Optional[int] | None | The number of threads single onnxruntime session can use. | | `prefix` | str | "" | A string to add to the beginning of each text. | | `suffix` | str | "" | A string to add to the end of each text. | | `batch_size` | int | 256 | Number of strings to encode at once. | | `progress_bar` | bool | True | If `True`, displays progress bar during embedding. | | `parallel` | Optional[int] | None | If > 1, data-parallel encoding is used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. | | `local_files_only` | bool | False | If `True`, only use the model files in the `cache_dir`. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of meta fields that should be embedded along with the Document content. | | `embedding_separator` | str | \n | Separator used to concatenate the meta fields to the Document content. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents to embed. | --- ## FastembedRanker(Legacy-components) Rank documents based on their similarity to the query using Fastembed models. ## Key Features - Ranks documents from most to least semantically relevant to the query. - Uses [Fastembed](https://qdrant.github.io/fastembed/) reranking models for fast, efficient reranking. - Configurable number of results returned via `top_k`. - Supports embedding metadata fields alongside document content for richer reranking. - Improves quality of generated answers by surfacing the most relevant documents at the top. ## Configuration 1. Drag the `FastembedRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the reranking model name. You can find supported models in the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). - Set `top_k` to control how many documents to return. 4. Go to the **Advanced** tab to configure additional settings such as `batch_size`, `parallel`, and `meta_fields_to_embed`. ## Connections `FastembedRanker` accepts a query string and a list of documents as inputs. Connect it after a retriever or `DocumentJoiner` in a query pipeline. It outputs a ranked list of documents sorted from most to least relevant. Connect its `documents` output to `ChatPromptBuilder`, `AnswerBuilder`, or another downstream component. ## Source Code To check this component's source code, open [`ranker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/rankers/fastembed/ranker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml FastembedRanker: type: haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker init_parameters: model_name: Xenova/ms-marco-MiniLM-L-6-v2 top_k: 5 batch_size: 64 local_files_only: false meta_data_separator: "\n" ``` This query pipeline uses `FastembedRanker` to rerank documents after retrieval: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 FastembedRanker: type: haystack_integrations.components.rankers.fastembed.ranker.FastembedRanker init_parameters: model_name: Xenova/ms-marco-MiniLM-L-6-v2 top_k: 5 cache_dir: threads: batch_size: 64 parallel: local_files_only: false meta_fields_to_embed: meta_data_separator: "\n" ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: "You are a helpful assistant answering questions based on the provided documents." - role: user content: "Documents:\n{% for doc in documents %}\n{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: bm25_retriever.documents receiver: FastembedRanker.documents - sender: FastembedRanker.documents receiver: ChatPromptBuilder.documents - sender: FastembedRanker.documents receiver: answer_builder.documents - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies inputs: query: - bm25_retriever.query - FastembedRanker.query - ChatPromptBuilder.query - answer_builder.query filters: - bm25_retriever.filters outputs: documents: FastembedRanker.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents sorted from most similar to least similar to the query. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model_name` | str | Xenova/ms-marco-MiniLM-L-6-v2 | Fastembed model name. Check the list of supported models in the [Fastembed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/). | | `top_k` | int | 10 | The maximum number of documents to return. | | `cache_dir` | Optional[str] | None | The path to the cache directory. Can be set using the `FASTEMBED_CACHE_PATH` env variable. Defaults to `fastembed_cache` in the system's temp directory. | | `threads` | Optional[int] | None | The number of threads single onnxruntime session can use. | | `batch_size` | int | 64 | Number of strings to encode at once. | | `parallel` | Optional[int] | None | If > 1, data-parallel encoding is used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. | | `local_files_only` | bool | False | If `True`, only use the model files in the `cache_dir`. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of meta fields that should be concatenated with the document content for reranking. | | `meta_data_separator` | str | \n | Separator used to concatenate the meta fields to the Document content. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | --- ## FastembedSparseDocumentEmbedder Compute sparse document embeddings using Fastembed sparse models. ## Key Features - Uses [Fastembed](https://qdrant.github.io/fastembed/) sparse models such as SPLADE for sparse embedding generation. - Stores the computed sparse embedding in the `sparse_embedding` field of each document. - Supports hybrid search scenarios combining sparse and dense retrieval. - Configurable batch size and parallel processing for large datasets. - Supports embedding metadata fields alongside document content. ## Configuration 1. Drag the `FastembedSparseDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the sparse embedding model. You can find supported models in the [FastEmbed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/#supported-sparse-text-embedding-models). 4. Go to the **Advanced** tab to configure additional settings such as `batch_size`, `parallel`, `meta_fields_to_embed`, and `model_kwargs`. ## Connections `FastembedSparseDocumentEmbedder` receives a list of `documents` from converters or `DocumentSplitter` in an indexing pipeline. It outputs the same documents with their `sparse_embedding` field populated. Connect its output to `DocumentWriter` to store the embedded documents. ## Source Code To check this component's source code, open [`fastembed_sparse_document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_sparse_document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `FastembedSparseDocumentEmbedder` accepts a list of documents as input. In an indexing pipeline, connect it to converters such as `TextFileToDocument` or preprocessors such as `DocumentSplitter`. It outputs a list of documents with the `sparse_embedding` field populated. Connect its `documents` output to `DocumentWriter` to store the embedded documents. ## Usage Examples ### Basic Configuration ```yaml FastembedSparseDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_sparse_document_embedder.FastembedSparseDocumentEmbedder init_parameters: model: prithivida/Splade_PP_en_v1 batch_size: 32 progress_bar: true local_files_only: false embedding_separator: "\n" ``` This index uses `FastembedSparseDocumentEmbedder` to create sparse embeddings: ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 5 split_overlap: 1 FastembedSparseDocumentEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_sparse_document_embedder.FastembedSparseDocumentEmbedder init_parameters: model: prithivida/Splade_PP_en_v1 cache_dir: threads: batch_size: 32 progress_bar: true parallel: local_files_only: false meta_fields_to_embed: embedding_separator: "\n" model_kwargs: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'sparse-index' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: policy: OVERWRITE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: FastembedSparseDocumentEmbedder.documents - sender: FastembedSparseDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents to embed. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents with each Document's `sparse_embedding` field set to the computed embeddings. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | prithivida/Splade_PP_en_v1 | Local path or name of the model in Hugging Face's model hub, such as `prithivida/Splade_PP_en_v1`. | | `cache_dir` | Optional[str] | None | The path to the cache directory. Can be set using the `FASTEMBED_CACHE_PATH` env variable. Defaults to `fastembed_cache` in the system's temp directory. | | `threads` | Optional[int] | None | The number of threads single onnxruntime session can use. | | `batch_size` | int | 32 | Number of strings to encode at once. | | `progress_bar` | bool | True | If `True`, displays progress bar during embedding. | | `parallel` | Optional[int] | None | If > 1, data-parallel encoding is used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. | | `local_files_only` | bool | False | If `True`, only use the model files in the `cache_dir`. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of meta fields that should be embedded along with the Document content. | | `embedding_separator` | str | \n | Separator used to concatenate the meta fields to the Document content. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Dictionary containing model parameters such as `k`, `b`, `avg_len`, `language`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | List of Documents to embed. | --- ## FastembedSparseTextEmbedder Compute sparse text embeddings using Fastembed sparse models. ## Key Features - Uses [Fastembed](https://qdrant.github.io/fastembed/) sparse models such as SPLADE for sparse text embedding. - Outputs a sparse embedding that can be used for sparse retrieval. - Useful in hybrid search scenarios combining sparse and dense retrieval. - Must use the same sparse embedding model as `FastembedSparseDocumentEmbedder` used in the index. ## Configuration 1. Drag the `FastembedSparseTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the sparse embedding model. You can find supported models in the [FastEmbed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/#supported-sparse-text-embedding-models). 4. Go to the **Advanced** tab to configure additional settings such as `parallel` and `model_kwargs`. ## Connections `FastembedSparseTextEmbedder` receives a `text` string (the user query) as input. It outputs a `sparse_embedding` object. Connect its output to a sparse retriever to find matching documents. Use the same sparse embedding model as the one used to embed documents in the document store. ## Source Code To check this component's source code, open [`fastembed_sparse_text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_sparse_text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `FastembedSparseTextEmbedder` accepts a text string as input. In a query pipeline, connect its `text` input to the `query` output of the `Input` component. It outputs a `SparseEmbedding`. Connect its `sparse_embedding` output to the `query_sparse_embedding` input of a sparse retriever. ## Usage Examples ### Basic Configuration ```yaml FastembedSparseTextEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_sparse_text_embedder.FastembedSparseTextEmbedder init_parameters: model: prithivida/Splade_PP_en_v1 progress_bar: true local_files_only: false ``` This query pipeline uses `FastembedSparseTextEmbedder` for sparse retrieval: ```yaml # haystack-pipeline components: FastembedSparseTextEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_sparse_text_embedder.FastembedSparseTextEmbedder init_parameters: model: prithivida/Splade_PP_en_v1 cache_dir: threads: progress_bar: true parallel: local_files_only: false model_kwargs: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: "You are a helpful assistant answering questions based on the provided documents." - role: user content: "Documents:\n{% for doc in documents %}\n{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: bm25_retriever.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies - sender: bm25_retriever.documents receiver: answer_builder.documents inputs: query: - bm25_retriever.query - ChatPromptBuilder.query - answer_builder.query filters: - bm25_retriever.filters outputs: documents: bm25_retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string to embed. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `sparse_embedding` | SparseEmbedding | | A sparse embedding representing the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | prithivida/Splade_PP_en_v1 | Local path or name of the model in Fastembed's model hub, such as `prithivida/Splade_PP_en_v1`. | | `cache_dir` | Optional[str] | None | The path to the cache directory. Can be set using the `FASTEMBED_CACHE_PATH` env variable. Defaults to `fastembed_cache` in the system's temp directory. | | `threads` | Optional[int] | None | The number of threads single onnxruntime session can use. | | `progress_bar` | bool | True | If `True`, displays progress bar during embedding. | | `parallel` | Optional[int] | None | If > 1, data-parallel encoding is used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. | | `local_files_only` | bool | False | If `True`, only use the model files in the `cache_dir`. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Dictionary containing model parameters such as `k`, `b`, `avg_len`, `language`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string to embed. | --- ## FastembedTextEmbedder(Legacy-components) Compute text embeddings using Fastembed embedding models. ## Key Features - Uses [Fastembed](https://qdrant.github.io/fastembed/), a lightweight, fast Python library for embedding generation. - Outputs a dense embedding vector for the input text. - Must use the same embedding model as `FastembedDocumentEmbedder` used in the index. - Supports optional text prefix and suffix for models that require instruction-style input. ## Configuration 1. Drag the `FastembedTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Select the embedding model. You can find supported models in the [FastEmbed documentation](https://qdrant.github.io/fastembed/examples/Supported_Models/#supported-text-embedding-models). 4. Go to the **Advanced** tab to configure additional settings such as `prefix`, `suffix`, `parallel`, and `local_files_only`. ## Connections `FastembedTextEmbedder` receives a `text` string (the user query) as input. It outputs an `embedding` list of floats. Connect its output to an embedding retriever to find matching documents. Use the same model as the one used to embed documents in the document store. ## Source Code To check this component's source code, open [`fastembed_text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/fastembed/src/haystack_integrations/components/embedders/fastembed/fastembed_text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `FastembedTextEmbedder` accepts a text string as input. In a query pipeline, connect its `text` input to the `query` output of the `Input` component. It outputs a dense embedding vector as `List[float]`. Connect its `embedding` output to the `query_embedding` input of an embedding retriever. ## Usage Examples ### Basic Configuration ```yaml FastembedTextEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 prefix: '' suffix: '' progress_bar: true local_files_only: false ``` This query pipeline uses `FastembedTextEmbedder` to embed the query for semantic search: ```yaml # haystack-pipeline components: FastembedTextEmbedder: type: haystack_integrations.components.embedders.fastembed.fastembed_text_embedder.FastembedTextEmbedder init_parameters: model: BAAI/bge-small-en-v1.5 cache_dir: threads: prefix: "" suffix: "" progress_bar: true parallel: local_files_only: false embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 384 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - role: system content: "You are a helpful assistant answering questions based on the provided documents." - role: user content: "Documents:\n{% for doc in documents %}\n{{ doc.content }}\n{% endfor %}\n\nQuestion: {{ query }}" OpenAIChatGenerator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: FastembedTextEmbedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ChatPromptBuilder.documents - sender: ChatPromptBuilder.prompt receiver: OpenAIChatGenerator.messages - sender: OpenAIChatGenerator.replies receiver: OutputAdapter.replies - sender: OutputAdapter.output receiver: answer_builder.replies - sender: embedding_retriever.documents receiver: answer_builder.documents inputs: query: - FastembedTextEmbedder.text - ChatPromptBuilder.query - answer_builder.query filters: - embedding_retriever.filters outputs: documents: embedding_retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string to embed. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `embedding` | List[float] | | A list of floats representing the embedding of the input text. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | BAAI/bge-small-en-v1.5 | Local path or name of the model in Fastembed's model hub, such as `BAAI/bge-small-en-v1.5`. | | `cache_dir` | Optional[str] | None | The path to the cache directory. Can be set using the `FASTEMBED_CACHE_PATH` env variable. Defaults to `fastembed_cache` in the system's temp directory. | | `threads` | Optional[int] | None | The number of threads single onnxruntime session can use. | | `prefix` | str | "" | A string to add to the beginning of each text. | | `suffix` | str | "" | A string to add to the end of each text. | | `progress_bar` | bool | True | If `True`, displays progress bar during embedding. | | `parallel` | Optional[int] | None | If > 1, data-parallel encoding is used, recommended for offline encoding of large datasets. If 0, use all available cores. If None, don't use data-parallel processing, use default onnxruntime threading instead. | | `local_files_only` | bool | False | If `True`, only use the model files in the `cache_dir`. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string to embed. | --- ## HuggingFaceLocalGenerator Generate text using models from Hugging Face that run locally. :::caution text2text-generation deprecated The `text2text-generation` task is deprecated and may be removed in a future release. In `transformers` v5+, `text2text-generation` is no longer available as a valid pipeline task. If you currently use `task="text2text-generation"`, replace it with `task="text-generation"` and ensure the selected model is compatible. To use the older behavior, pin `transformers<5`. ::: ## Key Features - Runs Hugging Face LLMs locally, without external API calls. - Supports decoder models like GPT and Qwen with the `text-generation` task. - Accepts configurable generation parameters such as `max_new_tokens` and `temperature`. - Supports streaming responses via a callback function. - Uses a Hugging Face API token for downloading private or gated models. ## Configuration 1. Drag the `HuggingFaceLocalGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name or path. Connect the platform to Hugging Face first. For instructions, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). - Set the `task` parameter. The default is `text-generation`, which works with decoder models like GPT and Qwen. 4. Go to the **Advanced** tab to configure `generation_kwargs` (such as `max_new_tokens`, `temperature`), `huggingface_pipeline_kwargs`, `stop_words`, and `device`. ## Connections `HuggingFaceLocalGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings. Connect its `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`hugging_face_local.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/hugging_face_local.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml HuggingFaceLocalGenerator: type: haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator init_parameters: model: Qwen/Qwen3-0.6B task: text-generation token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: max_new_tokens: 100 temperature: 0.9 ``` This query pipeline uses `HuggingFaceLocalGenerator` for local text generation: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 10 fuzziness: 0 PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Given the following information, answer the question. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }} required_variables: variables: HuggingFaceLocalGenerator: type: haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator init_parameters: model: Qwen/Qwen3-0.6B task: text-generation device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false generation_kwargs: max_new_tokens: 100 temperature: 0.9 huggingface_pipeline_kwargs: stop_words: streaming_callback: AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: bm25_retriever.documents receiver: PromptBuilder.documents - sender: PromptBuilder.prompt receiver: HuggingFaceLocalGenerator.prompt - sender: HuggingFaceLocalGenerator.replies receiver: AnswerBuilder.replies - sender: bm25_retriever.documents receiver: AnswerBuilder.documents inputs: query: - bm25_retriever.query - PromptBuilder.query - AnswerBuilder.query outputs: answers: AnswerBuilder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | A string representing the prompt. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[str] | | A list of strings representing the generated replies. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | Qwen/Qwen3-0.6B | The Hugging Face text generation model name or path. | | `task` | Optional[Literal['text-generation', 'text2text-generation']] | text-generation | The task for the Hugging Face pipeline. The default is `text-generation`, supported by decoder models like GPT and Qwen. The `text2text-generation` task (encoder-decoder models like T5) is deprecated and not available in `transformers` v5+. If not specified, the component infers the task from the model name. | | `device` | Optional[ComponentDevice] | None | The device for loading the model. If `None`, automatically selects the default device. If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The token to use as HTTP bearer authorization for remote files. If the token is specified in `huggingface_pipeline_kwargs`, this parameter is ignored. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary with keyword arguments to customize text generation: `max_length`, `max_new_tokens`, `temperature`, `top_k`, `top_p`. See [Hugging Face documentation](https://huggingface.co/docs/transformers/main/en/generation_strategies#customize-text-generation). | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | Dictionary with keyword arguments to initialize the Hugging Face pipeline. These override `model`, `task`, `device`, and `token` init parameters. See [Hugging Face documentation](https://huggingface.co/docs/transformers/en/main_classes/pipelines#transformers.pipeline.task). | | `stop_words` | Optional[List[str]] | None | If the model generates a stop word, the generation stops. If you provide this parameter, don't specify `stopping_criteria` in `generation_kwargs`. | | `streaming_callback` | Optional[StreamingCallbackT] | None | An optional callable for handling streaming responses. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | A string representing the prompt. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function that is called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) --- ## ListJoiner # ListJoiner (Legacy) A legacy component that joins multiple lists into a single flat list. :::info Legacy Component With [smart connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections), components can accept connections from multiple lists of the same type, making `ListJoiner` no longer necessary. It's no longer available in Builder's component library but you can still use and configure it through YAML. To learn how to remove it from your pipelines, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). ::: ## Key Features - Receives multiple lists of the same type and concatenates them into a single flat list. - Output order respects the pipeline's execution sequence, with earlier inputs being added first. - Useful for combining list outputs from multiple components. ## Configuration `ListJoiner` is no longer available in Pipeline Builder's component library. Configure it through the pipeline YAML directly. ## Connections `ListJoiner` accepts multiple list inputs through its `values` input. Connect any component that outputs lists of the same type, such as generators that output `List[ChatMessage]` or other list-producing components. It outputs the joined list through its `values` output. Connect it to any downstream component that accepts a list input. ## Source Code To check this component's source code, open [`list_joiner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/joiners/list_joiner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml ListJoiner: type: haystack.components.joiners.list_joiner.ListJoiner init_parameters: list_type_: list[haystack.dataclasses.document.Document] ``` This example shows an index that converts different file types (text, markdown, PDF) and joins all documents into a single list for processing. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: store_full_path: false PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: store_full_path: false ListJoiner: type: haystack.components.joiners.list_joiner.ListJoiner init_parameters: list_type_: list[haystack.dataclasses.document.Document] DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: sentence split_length: 100 split_overlap: 0 split_threshold: 0 splitting_function: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: OVERWRITE document_store: type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore init_parameters: bm25_tokenization_regex: (?u)\b\w\w+\b bm25_algorithm: BM25L bm25_parameters: embedding_similarity_function: dot_product index: 'default' async_executor: return_embedding: true FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - application/pdf - text/markdown - text/plain additional_mimetypes: raise_on_failure: false connections: - sender: TextFileToDocument.documents receiver: ListJoiner.values - sender: MarkdownToDocument.documents receiver: ListJoiner.values - sender: PDFMinerToDocument.documents receiver: ListJoiner.values - sender: ListJoiner.values receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DocumentWriter.documents - sender: FileTypeRouter.application/pdf receiver: PDFMinerToDocument.sources - sender: FileTypeRouter.text/markdown receiver: MarkdownToDocument.sources - sender: FileTypeRouter.text/plain receiver: TextFileToDocument.sources max_runs_per_component: 100 metadata: {} inputs: files: - FileTypeRouter.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `values` | Variadic[List[Any]] | | The lists to be joined. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `list_type_` | Optional[Type] | None | The expected type of the lists this component will join (for example, List[ChatMessage]). If specified, all input lists must conform to this type. If None, the component defaults to handling lists of any type including mixed types. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `values` | Variadic[List[Any]] | | The list to be joined. | --- ## LlamaCppChatGenerator(Legacy-components) Complete chats using large language models running on llama.cpp. ## Key Features - Runs LLMs locally using [llama.cpp](https://github.com/ggerganov/llama.cpp), a C/C++ library for efficient LLM inference. - Uses the quantized GGUF format, which reduces memory requirements and enables running on standard machines without GPUs. - Accepts `ChatMessage` objects as input and returns generated replies as `ChatMessage` objects. - Supports tool calls for agentic workflows. - Compatible with any GGUF-format model available on [Hugging Face](https://huggingface.co/models?library=gguf). ## Configuration Before using this component, download the GGUF version of the model you want from [Hugging Face](https://huggingface.co/models?library=gguf) and save it locally. 1. Drag the `LlamaCppChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `model` parameter to the local path of the GGUF file (for example, `/Downloads/gemma-3-1b-it-q4_0.gguf`). 4. Go to the **Advanced** tab to configure `n_ctx`, `n_batch`, `model_kwargs`, and `generation_kwargs`. ## Connections `LlamaCppChatGenerator` accepts a list of `ChatMessage` objects as input. Connect its `messages` input to the `prompt` output of `ChatPromptBuilder`. It outputs `replies` as a list of `ChatMessage` objects. Connect its `replies` output through `OutputAdapter` to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/llama_cpp/src/haystack_integrations/components/generators/llama_cpp/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LlamaCppChatGenerator: type: haystack_integrations.components.generators.llama_cpp.chat.chat_generator.LlamaCppChatGenerator init_parameters: model: /Downloads/gemma-3-1b-it-q4_0.gguf n_ctx: 0 n_batch: 512 ``` This is an example RAG pipeline with `LlamaCppChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false LlamaCppChatGenerator: type: haystack_integrations.components.generators.llama_cpp.chat.chat_generator.LlamaCppChatGenerator init_parameters: model: /Downloads/gemma-3-1b-it-q4_0.gguf n_ctx: 0 n_batch: 512 model_kwargs: generation_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: LlamaCppChatGenerator.messages - sender: LlamaCppChatGenerator.replies receiver: OutputAdapter.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of `ChatMessage` objects representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the arguments you can use, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_chat_completion). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[ChatMessage] | | The responses from the model. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | | The path of a quantized model for text generation, for example, "zephyr-7b-beta.Q4_0.gguf". If the model path is also specified in the `model_kwargs`, this parameter is ignored. | | `n_ctx` | Optional[int] | 0 | The number of tokens in the context. When set to 0, the context is taken from the model. | | `n_batch` | Optional[int] | 512 | Prompt processing maximum batch size. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Dictionary containing keyword arguments used to initialize the LLM for text generation. These keyword arguments provide fine-grained control over the model loading. In case of duplication, these kwargs override `model`, `n_ctx`, and `n_batch` init parameters. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.__init__). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_chat_completion). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a list of `Tool` objects or a `Toolset` instance. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_chat_completion). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it will override the `tools` parameter set in pipeline configuration. | --- ## LlamaCppGenerator Generate text using LLMs through llama.cpp. ## Key Features - Runs LLMs locally using [llama.cpp](https://github.com/ggerganov/llama.cpp), a C/C++ library for efficient LLM inference. - Uses the quantized GGUF format, suitable for running on standard machines without GPUs. - Accepts string prompts and returns string replies. - Compatible with any GGUF-format model available on [Hugging Face](https://huggingface.co/models?library=gguf). ## Configuration Before using this component, download the GGUF version of the model you want from [Hugging Face](https://huggingface.co/models?library=gguf) and save it locally. 1. Drag the `LlamaCppGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `model` parameter to the local path of the GGUF file (for example, `/models/zephyr-7b-beta.Q4_0.gguf`). 4. Go to the **Advanced** tab to configure `n_ctx`, `n_batch`, `model_kwargs`, and `generation_kwargs`. ## Connections `LlamaCppGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings and `meta` as a list of metadata dictionaries. Connect its `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/llama_cpp/src/haystack_integrations/components/generators/llama_cpp/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LlamaCppGenerator: type: haystack_integrations.components.generators.llama_cpp.generator.LlamaCppGenerator init_parameters: model: /models/zephyr-7b-beta.Q4_0.gguf n_ctx: 2048 n_batch: 512 generation_kwargs: max_tokens: 256 temperature: 0.7 top_p: 0.9 ``` ## Connections This example shows a simple question-answering pipeline using `LlamaCppGenerator` with a locally hosted GGUF model: ```yaml # haystack-pipeline components: PromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: | Answer the following question concisely and accurately. Question: {{ question }} Answer: LlamaCppGenerator: type: haystack_integrations.components.generators.llama_cpp.generator.LlamaCppGenerator init_parameters: model: /models/zephyr-7b-beta.Q4_0.gguf n_ctx: 2048 n_batch: 512 generation_kwargs: max_tokens: 256 temperature: 0.7 top_p: 0.9 AnswerBuilder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: connections: - sender: PromptBuilder.prompt receiver: LlamaCppGenerator.prompt - sender: LlamaCppGenerator.replies receiver: AnswerBuilder.replies max_runs_per_component: 100 metadata: {} inputs: question: - PromptBuilder.question - AnswerBuilder.query outputs: answers: AnswerBuilder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The prompt to be sent to the generative model. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. These kwargs are merged with any `generation_kwargs` set during initialization. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_completion). | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[str] | | The list of string replies generated by the model. | | `meta` | List[Dict[str, Any]] | | Metadata about the request, including completion details from llama.cpp. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | | The path of a quantized model for text generation, for example, "zephyr-7b-beta.Q4_0.gguf". If the model path is also specified in the `model_kwargs`, this parameter is ignored. | | `n_ctx` | Optional[int] | 0 | The number of tokens in the context. When set to 0, the context is taken from the model. | | `n_batch` | Optional[int] | 512 | Prompt processing maximum batch size. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Dictionary containing keyword arguments used to initialize the LLM for text generation. These keyword arguments provide fine-grained control over the model loading. In case of duplication, these kwargs override `model`, `n_ctx`, and `n_batch` init parameters. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.__init__). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_completion). | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The prompt to be sent to the generative model. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | A dictionary containing keyword arguments to customize text generation. For more information on the available kwargs, see [llama.cpp documentation](https://llama-cpp-python.readthedocs.io/en/latest/api-reference/#llama_cpp.Llama.create_completion). | --- ## LlamaStackChatGenerator Generate text using models available on Llama Stack server. ## Key Features - Connects to a [Llama Stack Server](https://llama-stack.readthedocs.io/) that supports multiple inference providers including Ollama, Together AI, vLLM, and other cloud providers. - Accepts `ChatMessage` objects as input and returns generated replies as `ChatMessage` objects. - Supports streaming responses via a callback function. - Supports tool calls for agentic workflows. - Compatible with any text generation parameters valid for the OpenAI chat completion API. ## Configuration Before using this component, set up a Llama Stack Server with an inference provider and make sure a model is available. For a quick start, see the [Llama Stack documentation](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html). 1. Drag the `LlamaStackChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `model` parameter to the name of the model available on your Llama Stack Server inference provider. - Set `api_base_url` to your Llama Stack API base URL. The default is `http://localhost:8321/v1/openai/v1`. 4. Go to the **Advanced** tab to configure `timeout`, `max_retries`, `generation_kwargs`, and `http_client_kwargs`. ## Connections `LlamaStackChatGenerator` accepts a list of `ChatMessage` objects as input. Connect its `messages` input to the `prompt` output of `ChatPromptBuilder`. It outputs `replies` as a list of `ChatMessage` objects. Connect its `replies` output through `OutputAdapter` to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/llama_stack/src/haystack_integrations/components/generators/llama_stack/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml LlamaStackChatGenerator: type: haystack_integrations.components.generators.llama_stack.chat.chat_generator.LlamaStackChatGenerator init_parameters: model: ollama/llama3.2:3b api_base_url: http://localhost:8321/v1/openai/v1 ``` This is an example RAG pipeline with `LlamaStackChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false LlamaStackChatGenerator: type: haystack_integrations.components.generators.llama_stack.chat.chat_generator.LlamaStackChatGenerator init_parameters: model: ollama/llama3.2:3b api_base_url: http://localhost:8321/v1/openai/v1 streaming_callback: generation_kwargs: tools: timeout: max_retries: http_client_kwargs: connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: ChatPromptBuilder.prompt receiver: LlamaStackChatGenerator.messages - sender: LlamaStackChatGenerator.replies receiver: OutputAdapter.replies inputs: query: - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: documents: "meta_field_grouping_ranker.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when the model receives a new token from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization. | | `tools_strict` | Optional[bool] | None | Whether to enable strict schema adherence for tool calls. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[ChatMessage] | | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | | The name of the model to use for chat completion. This depends on the inference provider used for the Llama Stack Server. | | `api_base_url` | str | http://localhost:8321/v1/openai/v1 | The Llama Stack API base URL. If not specified, localhost is used with the default port 8321. | | `organization` | Optional[str] | None | Your organization ID. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. The callback function accepts `StreamingChunk` as an argument. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model. These parameters are sent directly to the Llama Stack endpoint. See the [Llama Stack API documentation](https://llama-stack.readthedocs.io/) for more details. Supported parameters include: `max_tokens`, `temperature`, `top_p`, `stream`, `safe_prompt`, `random_seed`, `response_format`. | | `timeout` | Optional[int] | None | Timeout for client calls. If not set, it defaults to either the `OPENAI_TIMEOUT` environment variable or 30 seconds. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. Each tool should have a unique name. | | `tools_strict` | bool | False | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. | | `max_retries` | Optional[int] | None | Maximum number of retries to contact the server after an internal error. If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable or five. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of `ChatMessage` instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization. | | `tools_strict` | Optional[bool] | None | Whether to enable strict schema adherence for tool calls. | --- ## LostInTheMiddleRanker Reorder documents so the most relevant ones appear at the beginning and end of the list, where LLMs tend to pay more attention. ## Key Features - Addresses the "lost in the middle" phenomenon where LLMs pay less attention to documents in the middle of a long context. - Reorders documents so the most relevant ones appear at the beginning and end of the list. - Works with any list of documents; no model inference required. - Configurable number of documents to return via `top_k`. ## Configuration 1. Drag the `LostInTheMiddleRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set `top_k` to control how many documents to return. ## Connections `LostInTheMiddleRanker` accepts a list of documents as input. Connect it after a retriever or `DocumentJoiner` in a query pipeline. It outputs a reordered list of documents. Connect its `documents` output to `ChatPromptBuilder` or `AnswerBuilder`. ## Source Code To check this component's source code, open [`lost_in_the_middle.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/lost_in_the_middle.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml LostInTheMiddleRanker: type: haystack.components.rankers.lost_in_the_middle.LostInTheMiddleRanker init_parameters: {} ``` ### Using the Component in a Pipeline This query pipeline reorders retrieved documents before sending them to an LLM: ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default top_k: 20 ranker: type: haystack.components.rankers.lost_in_the_middle.LostInTheMiddleRanker init_parameters: top_k: 10 llm: type: haystack.components.generators.chat.llm.LLM init_parameters: chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-4o-mini api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false user_prompt: |- {% message role="user" %} Answer based on the documents. {% for doc in documents %} {{ doc.content }} {% endfor %} Question: {{ query }} {% endmessage %} required_variables: - query - documents connections: - sender: retriever.documents receiver: ranker.documents - sender: ranker.documents receiver: llm.documents inputs: query: - retriever.query - llm.query outputs: messages: llm.last_message max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents to reorder. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Reordered list of documents with the most relevant ones at the beginning and end. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `top_k` | Optional[int] | None | The maximum number of documents to return. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents to reorder. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | --- ## MockedTextEmbedder A test component that returns a mocked embedding for a given text string. :::info Work in Progress We're working on adding pipeline examples and most common component connections. ::: ## Key Features - Returns a mocked dense embedding for testing purposes. - Useful for testing hybrid retrieval pipeline configurations without a real embedding model. ## Configuration 1. Drag the `MockedTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, no configuration is required. ## Connections `MockedTextEmbedder` accepts no inputs. It outputs a dense embedding vector as `list[float]`. Connect its `embedding` output to the `query_embedding` input of an embedding retriever. ## Usage Examples ### Basic Configuration ```yaml MockedTextEmbedder: type: opensearch.tests.test_open_search_hybrid_retriever.MockedTextEmbedder init_parameters: {} ``` ```yaml components: MockedTextEmbedder: type: opensearch.tests.test_open_search_hybrid_retriever.MockedTextEmbedder init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `embedding` | list[float] | | A mocked embedding vector. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| --- ## NvidiaGenerator Generate text using NVIDIA's models through the NVIDIA NIM API. ## Key Features - Connects to models self-hosted with [NVIDIA NIM](https://ai.nvidia.com) or hosted on the [NVIDIA API Catalog](https://build.nvidia.com/explore/discover). - Accepts string prompts and returns string replies. - Supports configurable generation parameters such as `temperature`, `top_p`, and `max_tokens` via `model_arguments`. - Requires an NVIDIA API key set via the `NVIDIA_API_KEY` environment variable. ## Configuration 1. Drag the `NvidiaGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. See [NVIDIA NIMs](https://ai.nvidia.com) for supported models. - Set the NVIDIA API key. Connect the platform to NVIDIA first. For instructions, see [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx). 4. Go to the **Advanced** tab to configure `api_url`, `model_arguments`, and `timeout`. ## Connections `NvidiaGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings and `meta` as a list of metadata dictionaries. Connect its `replies` output to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/nvidia/src/haystack_integrations/components/generators/nvidia/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml NvidiaGenerator: type: haystack_integrations.components.generators.nvidia.generator.NvidiaGenerator init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: meta/llama3-70b-instruct api_url: https://integrate.api.nvidia.com/v1 model_arguments: temperature: 0.2 top_p: 0.7 max_tokens: 1024 ``` This pipeline uses `NvidiaGenerator` to generate replies to a question. It uses `DeepsetAnswerBuilder` to build the answers with references. ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 1024 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine top_k: 10 NvidiaTextEmbedder: type: haystack_integrations.components.embedders.nvidia.text_embedder.NvidiaTextEmbedder init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: nvidia/nv-embedqa-e5-v5 api_url: https://integrate.api.nvidia.com/v1 prefix: '' suffix: '' truncate: timeout: prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, for example [3] for Document [3]. Never name the documents, only enter a number in square brackets as a reference. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}]: {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. {% endif %} Question: {{ question }} Answer: NvidiaGenerator: type: haystack_integrations.components.generators.nvidia.generator.NvidiaGenerator init_parameters: api_key: type: env_var env_vars: - NVIDIA_API_KEY strict: true model: meta/llama3-70b-instruct api_url: https://integrate.api.nvidia.com/v1 model_arguments: temperature: 0.2 top_p: 0.7 max_tokens: 1024 timeout: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: NvidiaTextEmbedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: NvidiaGenerator.prompt - sender: NvidiaGenerator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt inputs: query: - NvidiaTextEmbedder.text - prompt_builder.question - answer_builder.query filters: - retriever.filters outputs: documents: retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | Text to be sent to the generative model. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[str] | | A list of replies generated by the model. | | `meta` | List[Dict[str, Any]] | | Information about the request, such as token count and model details. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | Optional[str] | None | Name of the model to use for text generation. See the [NVIDIA NIMs](https://ai.nvidia.com) for more information on the supported models. | | `api_key` | Optional[Secret] | Secret.from_env_var('NVIDIA_API_KEY') | API key for the NVIDIA NIM. Set it as the `NVIDIA_API_KEY` environment variable or pass it here. | | `api_url` | str | os.getenv('NVIDIA_API_URL', DEFAULT_API_URL) | Custom API URL for the NVIDIA NIM. | | `model_arguments` | Optional[Dict[str, Any]] | None | Additional arguments to pass to the model provider. These arguments are specific to a model. Search your model in the [NVIDIA NIM](https://ai.nvidia.com) to find the arguments it accepts. | | `timeout` | Optional[float] | None | Timeout for request calls, if not set it is inferred from the `NVIDIA_TIMEOUT` environment variable or set to 60 by default. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | Text to be sent to the generative model. | ## Related Information - [Use NVIDIA Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-nvidia-models.mdx) --- ## OllamaChatGenerator(Legacy-components) Generate text using models running on Ollama. ## Key Features - Connects to models served by [Ollama](https://ollama.ai), a project for running LLMs locally. - Uses the quantized GGUF format by default, enabling LLMs on standard machines without GPUs. - Accepts `ChatMessage` objects as input and returns generated replies as `ChatMessage` objects. - Supports streaming responses via a callback function. - Supports tool calls for agentic workflows. - Supports structured JSON output via the `response_format` parameter. ## Configuration 1. Drag the `OllamaChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. The model must already be available in your running Ollama instance. For a full list of supported models, see [Ollama's documentation](https://ollama.ai/docs/models/list). - Set the `url` to point to your Ollama server (default: `http://localhost:11434`). 4. Go to the **Advanced** tab to configure `timeout`, `keep_alive`, `generation_kwargs`, and `response_format`. ## Connections `OllamaChatGenerator` accepts a list of `ChatMessage` objects as input. Connect its `messages` input to the `prompt` output of `ChatPromptBuilder`. It outputs `replies` as a list of `ChatMessage` objects. Connect its `replies` output through `OutputAdapter` to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`chat_generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/generators/ollama/chat/chat_generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaChatGenerator: type: haystack_integrations.components.generators.ollama.chat.chat_generator.OllamaChatGenerator init_parameters: model: orca-mini url: http://localhost:11434 timeout: 120 ``` This is an example RAG pipeline with `OllamaChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm ChatPromptBuilder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering the user's questions based on the provided documents.\nIf the answer is not in the documents, rely on the web_search tool to find information.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Provided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}] :\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user required_variables: variables: OutputAdapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] custom_filters: unsafe: false OllamaChatGenerator: type: haystack_integrations.components.generators.ollama.chat.chat_generator.OllamaChatGenerator init_parameters: model: orca-mini url: http://localhost:11434 generation_kwargs: timeout: 120 keep_alive: streaming_callback: tools: response_format: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: meta_field_grouping_ranker.documents receiver: ChatPromptBuilder.documents - sender: OutputAdapter.output receiver: answer_builder.replies - sender: OllamaChatGenerator.replies receiver: OutputAdapter.replies - sender: ChatPromptBuilder.prompt receiver: OllamaChatGenerator.messages inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "answer_builder.query" - "ChatPromptBuilder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Per-call overrides for Ollama inference options. These are merged on top of the instance-level `generation_kwargs`. For a full list, see the [Ollama documentation](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callable to receive `StreamingChunk` objects as they arrive. Supplying a callback switches the component into streaming mode. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[ChatMessage] | | A list of ChatMessages containing the model's response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | orca-mini | The name of the model to use. The model must already be present (pulled) in the running Ollama instance. | | `url` | str | http://localhost:11434 | The base URL of the Ollama server. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama documentation](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `timeout` | int | 120 | The number of seconds before throwing a timeout error from the Ollama API. | | `keep_alive` | Optional[Union[float, str]] | None | Controls how long the model will stay loaded into memory following the request. If not set, it will use the default value from Ollama (five minutes). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of `haystack.tools.Tool` or a `haystack.tools.Toolset`. Not all models support tools. For a list of models compatible with tools, see the [models page](https://ollama.com/search?c=tools). | | `response_format` | Optional[Union[None, Literal['json'], JsonSchemaValue]] | None | The format for structured model outputs. The value can be: None (no specific format), "json" (JSON object), or a JSON Schema. | | `think` | bool | False | Whether to enable thinking mode for models that support it. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Per-call overrides for Ollama inference options. These are merged on top of the instance-level `generation_kwargs`. For a complete list of arguments, see the [Ollama documentation](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callable to receive `StreamingChunk` objects as they arrive. Supplying a callback switches the component into streaming mode. | --- ## OllamaDocumentEmbedder(Legacy-components) Calculate document embeddings using Ollama models. ## Key Features - Uses [Ollama](https://github.com/jmorganca/ollama) to run embedding models locally, without external API services. - Stores the computed embedding in the `embedding` field of each document. - Compatible with embedding models available in [Ollama's library](https://ollama.ai/library). - Default model is `nomic-embed-text`. - Supports embedding metadata fields alongside document content. ## Configuration Before using this component, make sure you have a running Ollama instance with the embedding model pulled. 1. Drag the `OllamaDocumentEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. The model must already be available in your running Ollama instance. See other pre-built models in Ollama's [library](https://ollama.ai/library). - Set the `url` to point to your Ollama server (default: `http://localhost:11434`). 4. Go to the **Advanced** tab to configure `timeout`, `batch_size`, `meta_fields_to_embed`, and `embedding_separator`. ## Connections `OllamaDocumentEmbedder` accepts a list of documents as input. In an indexing pipeline, connect it to converters such as `TextFileToDocument` or preprocessors such as `DocumentSplitter`. It outputs a list of documents with the `embedding` field populated. Connect its `documents` output to `DocumentWriter` to store the embedded documents. To embed a query string instead of documents, use [`OllamaTextEmbedder`](./OllamaTextEmbedder.mdx). ## Source Code To check this component's source code, open [`document_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/embedders/ollama/document_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaDocumentEmbedder: type: haystack_integrations.components.embedders.ollama.document_embedder.OllamaDocumentEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 timeout: 120 prefix: '' suffix: '' progress_bar: true embedding_separator: "\n" batch_size: 32 ``` In this index, `OllamaDocumentEmbedder` receives documents from `DocumentSplitter` and embeds them. It then sends the embedded documents to `DocumentWriter`. The index uses the `nomic-embed-text` model, which means `OllamaTextEmbedder` in the query pipeline must use the same model. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: OllamaDocumentEmbedder: type: haystack_integrations.components.embedders.ollama.document_embedder.OllamaDocumentEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 generation_kwargs: timeout: 120 prefix: '' suffix: '' progress_bar: true meta_fields_to_embed: embedding_separator: "\n" batch_size: 32 DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: ollama-embeddings-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine policy: NONE connections: - sender: TextFileToDocument.documents receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: OllamaDocumentEmbedder.documents - sender: OllamaDocumentEmbedder.documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: files: - TextFileToDocument.sources ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to be converted to an embedding. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, etc. See the [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents with their embeddings added to the `embedding` field. | | `meta` | Dict[str, Any] | | Metadata about the request, including the model name. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | nomic-embed-text | The name of the model to use. The model should be available in the running Ollama instance. | | `url` | str | http://localhost:11434 | The URL of a running Ollama instance. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `timeout` | int | 120 | The number of seconds before throwing a timeout error from the Ollama API. | | `prefix` | str | | A string to add at the beginning of each text. | | `suffix` | str | | A string to add at the end of each text. | | `progress_bar` | bool | True | If `True`, shows a progress bar when running. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed along with the document text. | | `embedding_separator` | str | \n | Separator used to concatenate the metadata fields to the document text. | | `batch_size` | int | 32 | Number of documents to process at once. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to be converted to an embedding. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, etc. See the [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | --- ## OllamaGenerator Generate text using an LLM running on Ollama. ## Key Features - Connects to models served by [Ollama](https://github.com/jmorganca/ollama), a project for running LLMs locally. - Uses the quantized GGUF format by default, enabling LLMs on standard machines without GPUs. - Accepts string prompts and returns string replies. - Supports streaming responses via a callback function. - Configurable generation parameters such as `temperature`, `top_p`, and `num_predict` via `generation_kwargs`. ## Configuration Before using this component, make sure you have a running Ollama instance with the model pulled. 1. Drag the `OllamaGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. The model must already be available in your running Ollama instance. See other pre-built models in Ollama's [library](https://ollama.ai/library). - Set the `url` to point to your Ollama server (default: `http://localhost:11434`). 4. Go to the **Advanced** tab to configure `timeout`, `keep_alive`, `system_prompt`, `template`, `raw`, and `generation_kwargs`. ## Connections `OllamaGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings and `meta` as a list of metadata dictionaries. Connect its `replies` output to `DeepsetAnswerBuilder`. ## Source Code To check this component's source code, open [`generator.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/generators/ollama/generator.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaGenerator: type: haystack_integrations.components.generators.ollama.generator.OllamaGenerator init_parameters: model: llama3 url: http://localhost:11434 generation_kwargs: temperature: 0.7 num_predict: 1024 raw: false timeout: 120 ``` ## Connections This pipeline uses `OllamaGenerator` to generate replies to a question. ```yaml # haystack-pipeline components: retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine top_k: 10 OllamaTextEmbedder: type: haystack_integrations.components.embedders.ollama.text_embedder.OllamaTextEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 generation_kwargs: timeout: 120 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: required_variables: "*" template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, for example [3] for Document [3]. Never name the documents, only enter a number in square brackets as a reference. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}]: {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. {% endif %} Question: {{ question }} Answer: OllamaGenerator: type: haystack_integrations.components.generators.ollama.generator.OllamaGenerator init_parameters: model: llama3 url: http://localhost:11434 generation_kwargs: temperature: 0.7 num_predict: 1024 system_prompt: template: raw: false timeout: 120 streaming_callback: keep_alive: answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: OllamaTextEmbedder.embedding receiver: retriever.query_embedding - sender: retriever.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: OllamaGenerator.prompt - sender: OllamaGenerator.replies receiver: answer_builder.replies - sender: retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt inputs: query: - OllamaTextEmbedder.text - prompt_builder.question - answer_builder.query filters: - retriever.filters outputs: documents: retriever.documents answers: answer_builder.answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The prompt to generate a response for. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[str] | | A list of replies generated by the model. | | `meta` | List[Dict[str, Any]] | | Information about the request, such as token count and model details. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | orca-mini | The name of the model to use. The model should be available in the running Ollama instance. | | `url` | str | http://localhost:11434 | The URL of a running Ollama instance. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `system_prompt` | Optional[str] | None | Optional system message (overrides what is defined in the Ollama Modelfile). | | `template` | Optional[str] | None | The full prompt template (overrides what is defined in the Ollama Modelfile). | | `raw` | bool | False | If True, no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your API request. | | `timeout` | int | 120 | The number of seconds before throwing a timeout error from the Ollama API. | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | | `keep_alive` | Optional[Union[float, str]] | None | Controls how long the model will stay loaded into memory following the request. If not set, it will use the default value from Ollama (five minutes). | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The prompt to generate a response for. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `streaming_callback` | Optional[Callable[[StreamingChunk], None]] | None | A callback function that is called when a new token is received from the stream. | --- ## OllamaTextEmbedder(Legacy-components) Embed strings, such as user queries, using Ollama models. ## Key Features - Uses [Ollama](https://github.com/jmorganca/ollama) to run embedding models locally, without external API services. - Outputs a dense embedding vector for the input text. - Must use the same embedding model as `OllamaDocumentEmbedder` used in the index. - Default model is `nomic-embed-text`. - Compatible with embedding models available in [Ollama's library](https://ollama.ai/library). ## Configuration Before using this component, make sure you have a running Ollama instance with the embedding model pulled. 1. Drag the `OllamaTextEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. The model must already be available in your running Ollama instance. See other pre-built models in Ollama's [library](https://ollama.ai/library). - Set the `url` to point to your Ollama server (default: `http://localhost:11434`). 4. Go to the **Advanced** tab to configure `timeout` and `generation_kwargs`. ## Connections `OllamaTextEmbedder` accepts a `text` string as input. In a query pipeline, connect its `text` input to the `query` output of the `Input` component. It outputs a dense embedding vector as `List[float]`. Connect its `embedding` output to the `query_embedding` input of an embedding retriever. To embed documents in an index instead, use [`OllamaDocumentEmbedder`](./OllamaDocumentEmbedder.mdx). ## Source Code To check this component's source code, open [`text_embedder.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/ollama/src/haystack_integrations/components/embedders/ollama/text_embedder.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Usage Examples ### Basic Configuration ```yaml OllamaTextEmbedder: type: haystack_integrations.components.embedders.ollama.text_embedder.OllamaTextEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 timeout: 120 ``` This is an example query pipeline with `OllamaTextEmbedder` that embeds a query and sends it to `OpenSearchEmbeddingRetriever` to find matching documents. ```yaml # haystack-pipeline components: OllamaTextEmbedder: type: haystack_integrations.components.embedders.ollama.text_embedder.OllamaTextEmbedder init_parameters: model: nomic-embed-text url: http://localhost:11434 generation_kwargs: timeout: 120 OpenSearchEmbeddingRetriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: filters: top_k: 10 filter_policy: replace custom_query: raise_on_failure: true efficient_filtering: true document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: ollama-embeddings-index max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: similarity: cosine connections: - sender: OllamaTextEmbedder.embedding receiver: OpenSearchEmbeddingRetriever.query_embedding max_runs_per_component: 100 metadata: {} inputs: query: - OllamaTextEmbedder.text outputs: documents: OpenSearchEmbeddingRetriever.documents ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | Text to be converted to an embedding. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, etc. See the [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `embedding` | List[float] | | The embedding of the text. | | `meta` | Dict[str, Any] | | Metadata about the request, including the model name. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | nomic-embed-text | The name of the model to use. The model should be available in the running Ollama instance. | | `url` | str | http://localhost:11434 | The URL of a running Ollama instance. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, and others. See the available arguments in [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | | `timeout` | int | 120 | The number of seconds before throwing a timeout error from the Ollama API. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | Text to be converted to an embedding. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Optional arguments to pass to the Ollama generation endpoint, such as temperature, top_p, etc. See the [Ollama docs](https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values). | --- ## OpenAIChatGenerator Complete chats using OpenAI's large language models (LLMs). ## Key Features - Works with GPT-4, GPT-5, and o-series models via the OpenAI API. - Accepts `ChatMessage` objects as input and returns generated replies as `ChatMessage` objects. - Supports streaming responses via a callback function. - Supports tool calls for agentic workflows. - Supports customizable generation parameters via `generation_kwargs`. ## Configuration 1. Drag the `OpenAIChatGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. - Set the OpenAI API key. Connect the platform to your OpenAI account on the Integrations page first. For details, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). 4. Go to the **Advanced** tab to configure `api_base_url`, `timeout`, `max_retries`, `generation_kwargs`, and `http_client_kwargs`. ## Connections `OpenAIChatGenerator` accepts a list of `ChatMessage` objects as input. Connect its `messages` input to the `prompt` output of `ChatPromptBuilder`. It outputs `replies` as a list of `ChatMessage` objects. Connect its `replies` output through `OutputAdapter` to `DeepsetAnswerBuilder` or `AnswerBuilder`. ## Source Code To check this component's source code, open [`openai.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/openai.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml openai_chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: temperature: 0.7 max_tokens: 500 ``` This is an example RAG pipeline with `OpenAIChatGenerator` and `DeepsetAnswerBuilder` connected through `OutputAdapter`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 chat_prompt_builder: type: haystack.components.builders.chat_prompt_builder.ChatPromptBuilder init_parameters: template: - _content: - text: "You are a helpful assistant answering questions based on the provided documents.\nIf the documents don't contain the answer, say so.\nDo not use your own knowledge.\n" _role: system - _content: - text: "Documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\n" _role: user openai_chat_generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: model: gpt-5-mini generation_kwargs: temperature: 0.7 max_tokens: 500 output_adapter: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: template: '{{ replies[0] }}' output_type: List[str] answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: chat_prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: chat_prompt_builder.prompt receiver: openai_chat_generator.messages - sender: openai_chat_generator.replies receiver: output_adapter.replies - sender: output_adapter.output receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - chat_prompt_builder.query - answer_builder.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents answers: answer_builder.answers metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `messages` | List[ChatMessage] | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create). | | `tools` | Optional[Union[List[Tool], Toolset]] | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter set during component initialization. | | `tools_strict` | Optional[bool] | Whether to enable strict schema adherence for tool calls. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[ChatMessage] | A list containing the generated responses as `ChatMessage` instances. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | The OpenAI API key. Set it on the Integrations page. | | `model` | str | gpt-5-mini | The name of the model to use. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `api_base_url` | Optional[str] | None | An optional base URL. | | `organization` | Optional[str] | None | Your organization ID. See [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat) for more details. | | `timeout` | Optional[float] | 30.0 | Timeout for OpenAI client calls. If not set, it defaults to the `OPENAI_TIMEOUT` environment variable or 30 seconds. | | `max_retries` | Optional[int] | five | Maximum number of retries to contact OpenAI after an internal error. If not set, it defaults to the `OPENAI_MAX_RETRIES` environment variable or five. | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. | | `tools_strict` | boolean | False | Whether to enable strict schema adherence for tool calls. If set to `True`, the model follows exactly the schema provided in the `parameters` field of the tool definition, but this may increase latency. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `messages` | List[ChatMessage] | | A list of ChatMessage instances representing the input messages. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters in pipeline configuration. For supported parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create). | | `tools` | Optional[Union[List[Tool], Toolset]] | None | A list of tools or a Toolset for which the model can prepare calls. If set, it overrides the `tools` parameter in pipeline configuration. | | `tools_strict` | Optional[bool] | None | Whether to enable strict schema adherence for tool calls. If set, it overrides the `tools_strict` parameter in pipeline configuration. | ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) --- ## OpenAIGenerator Generate text using OpenAI's large language models (LLMs). ## Key Features - Works with GPT-4, GPT-5, and o-series models via the OpenAI API. - Accepts string prompts and returns string replies. - Supports streaming responses via a callback function. - Supports customizable generation parameters via `generation_kwargs`. - Supports optional system prompts to configure model behavior. ## Configuration 1. Drag the `OpenAIGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. - Set the OpenAI API key. Connect the platform to your OpenAI account on the Integrations page first. For details, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - Optionally, set a `system_prompt` to configure model behavior. 4. Go to the **Advanced** tab to configure `api_base_url`, `timeout`, `max_retries`, `generation_kwargs`, and `http_client_kwargs`. ## Connections `OpenAIGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings and `meta` as a list of metadata dictionaries. Connect its `replies` output to `AnswerBuilder`. ## Source Code To check this component's source code, open [`openai.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/openai.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-5-mini ``` Here's an example RAG pipeline using `OpenAIGenerator`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false timeout: top_k: 10 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a helpful assistant. Answer the question based on the provided documents. If the documents don't contain the answer, say so. Documents: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{question}} Answer: answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} OpenAIGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-5-mini streaming_callback: api_base_url: organization: system_prompt: generation_kwargs: timeout: max_retries: http_client_kwargs: connections: - sender: bm25_retriever.documents receiver: prompt_builder.documents - sender: bm25_retriever.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: OpenAIGenerator.prompt - sender: OpenAIGenerator.replies receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - prompt_builder.question - answer_builder.query outputs: answers: answer_builder.answers metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | | :--- | :--- | :--- | | `prompt` | str | The string prompt to use for text generation. | | `system_prompt` | Optional[str] | The system prompt to use for text generation. If this runtime system prompt is omitted, the system prompt defined at initialization time is used. | | `streaming_callback` | Optional[StreamingCallbackT] | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | Additional keyword arguments for text generation. These parameters override the parameters passed in the `__init__` method. For more details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create). | ### Outputs | Parameter | Type | Description | | :--- | :--- | :--- | | `replies` | List[str] | A list of strings containing the generated responses. | | `meta` | List[Dict[str, Any]] | A list of dictionaries containing metadata for each response, including model info and usage. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `api_key` | Secret | Secret.from_env_var('OPENAI_API_KEY') | The OpenAI API key to connect to OpenAI. | | `model` | str | gpt-5-mini | The name of the model to use. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `api_base_url` | Optional[str] | None | An optional base URL. | | `organization` | Optional[str] | None | The Organization ID. For help, see [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization). | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If not provided, the system prompt is omitted, and the default system prompt of the model is used. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Other parameters to use for the model, sent directly to the OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat) for more details. | | `timeout` | Optional[float] | 30.0 | Timeout for OpenAI client calls. If not set, it is inferred from the `OPENAI_TIMEOUT` environment variable or set to 30. | | `max_retries` | Optional[int] | five | Maximum retries to establish contact with OpenAI if it returns an internal error. If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to five. | | `http_client_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments to configure a custom `httpx.Client` or `httpx.AsyncClient`. For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client). | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | `prompt` | str | | The string prompt to use for text generation. | | `system_prompt` | Optional[str] | None | The system prompt to use for text generation. If this runtime system prompt is omitted, the system prompt defined at initialization time is used. | | `streaming_callback` | Optional[StreamingCallbackT] | None | A callback function called when a new token is received from the stream. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters override the parameters passed in the `__init__` method. For more details, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create). | ## Related Information - [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx) --- ## PromptBuilder Render a prompt filling in any variables and send it to a Generator. ## Key Features - Renders prompt templates using Jinja2 syntax, filling in variables from pipeline inputs. - Variables in the template become optional inputs for the component by default. - Supports required variable enforcement via the `required_variables` parameter. - Supports runtime template overrides and variable injection via `template_variables`. - Works with Generators that accept string prompts, such as `OpenAIGenerator` and `AmazonBedrockGenerator`. ## Configuration 1. Drag the `PromptBuilder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Enter your prompt template using Jinja2 syntax. For example: `"Answer this question: {{ query }}"`. Variables in the template become inputs for the component. - Optionally, set `required_variables` to define which variables must be provided. Use `"*"` to require all variables. 4. Go to the **Advanced** tab to configure optional input variables for prompt engineering scenarios via `variables`. ## Connections `PromptBuilder` accepts template variables as dynamic inputs. The inputs depend on the variables in your template. Connect document or text outputs from retrievers or rankers to the corresponding variable inputs. It outputs a rendered `prompt` string. Connect its `prompt` output to the `prompt` input of a Generator such as `OpenAIGenerator`. ## Source Code To check this component's source code, open [`prompt_builder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/builders/prompt_builder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: ``` This is a RAG pipeline that uses `PromptBuilder` with `OpenAIGenerator`: ```yaml # haystack-pipeline components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 query_embedder: type: haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder init_parameters: model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. Ignore typing errors in the question. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. Just output the structured, informative and precise answer and nothing else. If the documents can't answer the question, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3]. Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{ question }} Answer: llm: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": False} model: "gpt-4o" generation_kwargs: max_tokens: 400 temperature: 0.0 seed: 0 answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: prompt_builder.documents - sender: ranker.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies - sender: prompt_builder.prompt receiver: llm.prompt - sender: llm.replies receiver: answer_builder.replies max_runs_per_component: 100 inputs: query: - bm25_retriever.query - query_embedder.text - ranker.query - prompt_builder.question - answer_builder.query filters: - bm25_retriever.filters - embedding_retriever.filters outputs: documents: ranker.documents answers: answer_builder.answers metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `template` | Optional[str] | None | An optional string template to overwrite PromptBuilder's default template. | | `template_variables` | Optional[Dict[str, Any]] | None | An optional dictionary of template variables to overwrite the pipeline variables. | | `kwargs` | Any | | Pipeline variables used for rendering the prompt. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The updated prompt text after rendering the prompt template. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `template` | str | | A prompt template that uses Jinja2 syntax to add variables. For example: `"Summarize this document: {{ documents[0].content }}\nSummary:"`. Variables in the default template are inputs for PromptBuilder and are all optional unless explicitly specified. If an optional variable is not provided, it's replaced with an empty string in the rendered prompt. | | `required_variables` | Optional[Union[List[str], Literal['*']]] | None | List of variables that must be provided as input to PromptBuilder. If a required variable is missing, an exception is raised. If set to `"*"`, all variables found in the prompt are required. | | `variables` | Optional[List[str]] | None | List of input variables to use in prompt templates instead of the ones inferred from the `template` parameter. Useful for prompt engineering when you need more variables than the ones in the default template. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `template` | Optional[str] | None | An optional string template to overwrite PromptBuilder's default template. If None, the default template provided at initialization is used. | | `template_variables` | Optional[Dict[str, Any]] | None | An optional dictionary of template variables to overwrite the pipeline variables. | | `kwargs` | Any | | Pipeline variables used for rendering the prompt. | ## Related Information - [Writing Prompts in deepset AI Platform](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx) --- ## ReferencePredictor Use this component in retrieval augmented generation (RAG) pipelines to predict references for the generated answer. :::warning Deprecation Notice This component is deprecated. It will continue to work in your existing pipelines. You can use LLM-generated references instead. For more information, see [Enable References for Generated Answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx). ::: ## Key Features - Adds predicted references to generated answers, showing which source documents the answer is based on. - Uses a cross-encoder model to compare similarity between answer sentences and document sentences. - Supports a verifiability model to identify answers that may need verification. - The default model (`cross-encoder/ms-marco-MiniLM-L-6-v2`) only works for English data. - Adds a `_references` metadata field to each answer containing reference details. ## Configuration 1. Drag the `ReferencePredictor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the reference prediction model path or name. The default is `cross-encoder/ms-marco-MiniLM-L-6-v2`. 4. Go to the **Advanced** tab to configure `use_split_rules`, `extend_abbreviations`, `verifiability_model`, `batch_size`, and other parameters. ## Connections `ReferencePredictor` accepts a list of `GeneratedAnswer` objects as input. Connect its `answers` input to the `answers` output of a Generator or another answer-producing component. It outputs a list of `GeneratedAnswer` objects enriched with a `_references` metadata field. Connect its `answers` output to `AnswerBuilder` or to the pipeline `Output` component. ## Usage Examples ### Basic Configuration ```yaml reference_predictor: type: deepset_cloud_custom_nodes.augmenters.reference_predictor.ReferencePredictor init_parameters: use_split_rules: true extend_abbreviations: true ``` This is an example of a query pipeline in which `ReferencePredictor` sends answers with references to `AnswerBuilder`. ```yaml components: reference_predictor: type: deepset_cloud_custom_nodes.augmenters.reference_predictor.ReferencePredictor init_parameters: use_split_rules: true extend_abbreviations: true answer_builder: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: {} connections: - sender: reference_predictor.answers receiver: answer_builder.answers ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `answers` | List[GeneratedAnswer] | | The generated answers to which you want to add references. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `answers` | List[GeneratedAnswer] | | Generated answers with a metadata field `_references` added to each answer containing a list of references. Each reference contains: `document_start_idx`, `document_end_idx`, `answer_start_idx`, `answer_end_idx`, `score`, `document_id`, `document_position`, and `label`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | cross-encoder/ms-marco-MiniLM-L-6-v2 | The name identifier of the model to use on Hugging Face Hub or the path to a local model folder. | | `revision` | Optional[str] | None | The revision of the model to use. | | `max_seq_len` | int | 512 | The maximum number of tokens that a sequence should be truncated to before inference. | | `language` | Language | en | The language of the data to generate references for. The language is needed to apply the right sentence splitting rules. | | `device` | Optional[ComponentDevice] | None | The device on which the model is loaded. If `None`, the default device is automatically selected. | | `batch_size` | int | 16 | The batch size to use for inference. | | `answer_window_size` | int | 1 | How many sentences of an answer should be packed into one span for inference. | | `document_window_size` | int | 3 | How many sentences of a document should be packed into one span for inference. | | `token` | Optional[Secret] | Secret.from_env_var('HF_API_TOKEN', strict=False) | The token to use as HTTP bearer authorization for remote files. | | `function_to_apply` | str | sigmoid | What activation function to use on top of the logits. Available: sigmoid, softmax, none. | | `min_score_2_label_thresholds` | Optional[Dict] | None | The minimum prediction score threshold for each corresponding label. | | `label_2_score_map` | Optional[Dict] | None | If using a model with a multi-label prediction head, pass in a dict mapping label names to a float value that will be used as the score. | | `reference_threshold` | Optional[int] | None | If using this component to generate references for answer spans, you can pass in a minimum score threshold. If no threshold is passed, the reference is chosen by picking the maximum score. | | `default_class` | str | not_grounded | A fallback class to use if the predicted score doesn't match any threshold. | | `verifiability_model` | Optional[str] | tstadel/answer-classification-setfit-v2-binary | The name identifier of the verifiability model to use on Hugging Face Hub or the path to a local model folder. | | `verifiability_revision` | Optional[str] | None | The revision of the verifiability model to use. | | `verifiability_batch_size` | int | 32 | The batch size to use for verifiability inference. | | `needs_verification_classes` | List[str] or None | None | The class names to use to determine if a sentence needs verification. Defaults to `["needs_verification"]`. | | `use_split_rules` | bool | False | If True, additional rules for better splitting answers are applied to the sentence splitting tokenizer. | | `extend_abbreviations` | bool | False | If True, the abbreviations used by NLTK's PunktTokenizer are extended by a list of curated abbreviations if available. | | `answer_stride` | int | 1 | The stride size for the answer window. | | `document_stride` | int | 3 | The stride size for the document window. | | `model_kwargs` | Optional[Dict] | None | Additional keyword arguments for the model. | | `verifiability_model_kwargs` | Optional[Dict] | None | Additional keyword arguments for the verifiability model. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `answers` | List[GeneratedAnswer] | | Replies returned by the Generator. | ## Related Information - [Enable References for Generated Answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx) --- ## SagemakerGenerator(Legacy-components) Generate text using large language models deployed on Amazon Sagemaker. ## Key Features - Connects to LLMs hosted on a SageMaker Inference Endpoint. - Accepts string prompts and returns string replies. - Supports configurable generation parameters via `generation_kwargs`. - Supports custom attributes for models that require special initialization, such as Llama-2 models that require `accept_eula: True`. - Requires AWS credentials set via environment variables. ## Configuration 1. Drag the `SagemakerGenerator` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `model` parameter to the SageMaker Model Endpoint name. - Connect the platform with Amazon Bedrock first. ::: 1. Drag the `SagemakerGenerator` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. On the **General** tab: 1. Enter the SageMaker Model Endpoint name, such as `jumpstart-dft-meta-textgenerationneuron-llama-2-7b`. 4. Go to the **Advanced** tab to configure AWS credentials, custom attributes, and generation kwargs. ## Connections `SagemakerGenerator` receives a `prompt` string from `PromptBuilder`. It outputs `replies` (a list of generated strings) and `meta` (response metadata). Connect its `replies` output to `AnswerBuilder` or `DeepsetAnswerBuilder`. 4. Go to the **Advanced** tab to configure `generation_kwargs`, `aws_custom_attributes`, and AWS credential parameters. ## Source Code To check this component's source code, open [`sagemaker.py`](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/amazon_sagemaker/src/haystack_integrations/components/generators/amazon_sagemaker/sagemaker.py) in the [Haystack Core Integrations repository](https://github.com/deepset-ai/haystack-core-integrations). ## Connections `SagemakerGenerator` accepts a `prompt` string as input. Connect its `prompt` input to the `prompt` output of `PromptBuilder`. It outputs `replies` as a list of strings and `meta` as a list of metadata dictionaries. Connect its `replies` output to `DeepsetAnswerBuilder`. ## Usage Examples ### Basic Configuration ```yaml SagemakerGenerator: type: haystack_integrations.components.generators.amazon_sagemaker.sagemaker.SagemakerGenerator init_parameters: model: jumpstart-dft-meta-textgenerationneuron-llama-2-7b aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false aws_custom_attributes: - accept_eula: true ``` This is a RAG pipeline that uses `SagemakerGenerator` with a Llama2 model: ```yaml # haystack-pipeline components: bm25_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'Standard-Index-English' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 meta_field_grouping_ranker: type: haystack.components.rankers.meta_field_grouping_ranker.MetaFieldGroupingRanker init_parameters: group_by: file_id subgroup_by: sort_docs_by: split_id prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- You are a technical expert. You answer questions truthfully based on provided documents. If the answer exists in several documents, summarize them. Ignore documents that don't contain the answer to the question. Only answer based on the documents provided. Don't make things up. If no information related to the question can be found in the document, say so. Always use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document [3] . Never name the documents, only enter a number in square brackets as a reference. The reference must only refer to the number that comes in square brackets after the document. Otherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document. These are the documents: {%- if documents|length > 0 %} {%- for document in documents %} Document [{{ loop.index }}] : Name of Source File: {{ document.meta.file_name }} {{ document.content }} {% endfor -%} {%- else %} No relevant documents found. Respond with "Sorry, no matching documents were found, please adjust the filters or try a different question." {% endif %} Question: {{ question }} Answer: required_variables: "*" answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm LangfuseConnector: type: haystack_integrations.components.connectors.langfuse.langfuse_connector.LangfuseConnector init_parameters: name: RAG-QA-Claude-3.5-Sonnet-en public: false public_key: type: env_var env_vars: - LANGFUSE_PUBLIC_KEY strict: false secret_key: type: env_var env_vars: - LANGFUSE_SECRET_KEY strict: false httpx_client: span_handler: SagemakerGenerator: type: haystack_integrations.components.generators.amazon_sagemaker.sagemaker.SagemakerGenerator init_parameters: model: jumpstart-dft-meta-textgenerationneuron-llama-2-7b aws_access_key_id: type: env_var env_vars: - AWS_ACCESS_KEY_ID strict: false aws_secret_access_key: type: env_var env_vars: - AWS_SECRET_ACCESS_KEY strict: false aws_session_token: type: env_var env_vars: - AWS_SESSION_TOKEN strict: false aws_region_name: type: env_var env_vars: - AWS_DEFAULT_REGION strict: false aws_profile_name: type: env_var env_vars: - AWS_PROFILE strict: false aws_custom_attributes: - accept_eula: true generation_kwargs: connections: # Defines how the components are connected - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: meta_field_grouping_ranker.documents - sender: meta_field_grouping_ranker.documents receiver: prompt_builder.documents - sender: meta_field_grouping_ranker.documents receiver: answer_builder.documents - sender: prompt_builder.prompt receiver: answer_builder.prompt - sender: prompt_builder.prompt receiver: SagemakerGenerator.prompt - sender: SagemakerGenerator.replies receiver: answer_builder.replies inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "bm25_retriever.query" - "query_embedder.text" - "ranker.query" - "prompt_builder.question" - "answer_builder.query" filters: # These components will receive a potential query filter as input - "bm25_retriever.filters" - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "meta_field_grouping_ranker.documents" # The output of the pipeline is the retrieved documents answers: "answer_builder.answers" # The output of the pipeline is the generated answers max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The prompt with instructions for the model. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters potentially override the parameters passed in pipeline configuration. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `replies` | List[str] | | A list of strings containing the generated responses. | | `meta` | List[Dict[str, Any]] | | A list of dictionaries containing the metadata for each response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `aws_access_key_id` | Optional[Secret] | Secret.from_env_var(['AWS_ACCESS_KEY_ID'], strict=False) | The `Secret` for AWS access key ID. | | `aws_secret_access_key` | Optional[Secret] | Secret.from_env_var(['AWS_SECRET_ACCESS_KEY'], strict=False) | The `Secret` for AWS secret access key. | | `aws_session_token` | Optional[Secret] | Secret.from_env_var(['AWS_SESSION_TOKEN'], strict=False) | The `Secret` for AWS session token. | | `aws_region_name` | Optional[Secret] | Secret.from_env_var(['AWS_DEFAULT_REGION'], strict=False) | The `Secret` for AWS region name. If not provided, the default region will be used. | | `aws_profile_name` | Optional[Secret] | Secret.from_env_var(['AWS_PROFILE'], strict=False) | The `Secret` for AWS profile name. If not provided, the default profile will be used. | | `model` | str | | The name for SageMaker Model Endpoint. | | `aws_custom_attributes` | Optional[Dict[str, Any]] | None | Custom attributes to be passed to SageMaker, for example `{"accept_eula": True}` in case of Llama-2 models. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. For a list of supported parameters, see your model's documentation page. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `prompt` | str | | The string prompt to use for text generation. | | `generation_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for text generation. These parameters will potentially override the parameters passed in the `__init__` method. | --- ## SentenceTransformersDocumentImageEmbedder Compute image embeddings for a list of documents using Sentence Transformers models. ## Key Features - Uses Sentence Transformers models that can embed text and images into the same vector space. - Supports both direct image files and PDF documents by extracting specific pages as images. - Stores the computed embedding in the `embedding` field of each document. - Automatically handles image preprocessing including resizing and format conversion. - Suitable for multimodal applications. ## Configuration 1. Drag the `SentenceTransformersDocumentImageEmbedder` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name. Compatible models include `clip-ViT-B-32`, `clip-ViT-L-14`, `clip-ViT-B-16`, and others. - Set the `file_path_meta_field` to the metadata field that contains the file path to the image or PDF. - Connect the platform to your Hugging Face account to use private models. For instructions, see [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx). 4. Go to the **Advanced** tab to configure `batch_size`, `normalize_embeddings`, `device`, `trust_remote_code`, and other parameters. ## Connections `SentenceTransformersDocumentImageEmbedder` accepts a list of documents as input. Each document must have a valid file path in its metadata pointing to an image or PDF file. In an indexing pipeline, connect it to a retriever or directly provide documents. It outputs a list of documents with the `embedding` field populated. Connect its `documents` output to `DocumentWriter` to store the embedded documents. ## Source Code To check this component's source code, open [`sentence_transformers_doc_image_embedder.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/embedders/image/sentence_transformers_doc_image_embedder.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml document_image_embedder: type: haystack.components.embedders.image.SentenceTransformersDocumentImageEmbedder init_parameters: model: sentence-transformers/clip-ViT-B-32 file_path_meta_field: file_path normalize_embeddings: true ``` This is an index that uses `SentenceTransformersDocumentImageEmbedder` to embed documents with images: ```yaml # haystack-pipeline components: document_image_embedder: type: haystack.components.embedders.image.SentenceTransformersDocumentImageEmbedder init_parameters: model: sentence-transformers/clip-ViT-B-32 file_path_meta_field: file_path normalize_embeddings: true document_writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: - ${OPENSEARCH_HOST} http_auth: - ${OPENSEARCH_USER} - ${OPENSEARCH_PASSWORD} use_ssl: true verify_certs: false index: my_index embedding_dim: 512 connections: - sender: document_image_embedder.documents receiver: document_writer.documents inputs: documents: - document_image_embedder.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to embed. Each document must have a valid file path in its metadata pointing to an image or PDF file. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents with embeddings stored in the `embedding` field. Each document also includes metadata about the embedding source. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `file_path_meta_field` | str | file_path | The metadata field in the Document that contains the file path to the image or PDF. | | `root_path` | Optional[str] | None | The root directory path where document files are located. If provided, file paths in document metadata will be resolved relative to this path. If None, file paths are treated as absolute paths. | | `model` | str | sentence-transformers/clip-ViT-B-32 | The Sentence Transformers model to use for calculating embeddings. Must be able to embed images and text into the same vector space. | | `device` | Optional[ComponentDevice] | None | The device to use for loading the model. Overrides the default device. | | `token` | Optional[Secret] | None | The API token to download private models from Hugging Face. | | `batch_size` | int | 32 | Number of documents to embed at once. | | `progress_bar` | bool | True | If `True`, shows a progress bar when embedding documents. | | `normalize_embeddings` | bool | False | If `True`, the embeddings are normalized using L2 normalization, so that each embedding has a norm of 1. | | `trust_remote_code` | bool | False | If `False`, allows only Hugging Face verified model architectures. If `True`, allows custom models and scripts. | | `local_files_only` | bool | False | If `True`, does not attempt to download the model from Hugging Face Hub and only looks at local files. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `precision` | Literal | float32 | The precision to use for the embeddings. All non-float32 precisions are quantized embeddings. | | `encode_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `SentenceTransformer.encode` when embedding documents. | | `backend` | Literal | torch | The backend to use for the Sentence Transformers model. Choose from "torch", "onnx", or "openvino". | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to embed. Each document must have a valid file path in its metadata pointing to an image or PDF file. | ## Related Information - [Use Hugging Face Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-hugging-face-models.mdx) --- ## SentenceTransformersSimilarityRanker Rank documents based on their semantic similarity to the query. ## Key Features - Uses a pre-trained cross-encoder model from Hugging Face to rank documents by semantic similarity to the query. - Configurable number of results returned via `top_k`. - Supports score scaling via Sigmoid activation for normalized similarity scores. - Supports filtering by score threshold. - Supports multiple backends: torch, ONNX, and OpenVINO. ## Configuration 1. Drag the `SentenceTransformersSimilarityRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the ranking model. Pass a local path or the Hugging Face model name of a cross-encoder model. - Set `top_k` to control how many documents to return. 4. Go to the **Advanced** tab to configure `scale_score`, `score_threshold`, `batch_size`, `backend`, and `meta_fields_to_embed`. ## Connections `SentenceTransformersSimilarityRanker` accepts a query string and a list of documents as inputs. Connect it after a retriever or `DocumentJoiner` in a query pipeline. It outputs a ranked list of documents sorted from most to least relevant to the query. Connect its `documents` output to `ChatPromptBuilder`, `AnswerBuilder`, or another downstream component. ## Source Code To check this component's source code, open [`sentence_transformers_similarity.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/sentence_transformers_similarity.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml SentenceTransformersSimilarityRanker: type: haystack.components.rankers.sentence_transformers_similarity.SentenceTransformersSimilarityRanker init_parameters: {} ``` ```yaml # haystack-pipeline components: SentenceTransformersSimilarityRanker: type: haystack.components.rankers.sentence_transformers_similarity.SentenceTransformersSimilarityRanker init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `scale_score` | Optional[bool] | None | If `True`, scales the raw logit predictions using a Sigmoid activation function. If `False`, disables scaling. If set, overrides the value set at initialization. | | `score_threshold` | Optional[float] | None | Return documents only with a score above this threshold. If set, overrides the value set at initialization. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents closest to the query, sorted from most similar to least similar. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | Union[str, Path] | cross-encoder/ms-marco-MiniLM-L-6-v2 | The ranking model. Pass a local path or the Hugging Face model name of a cross-encoder model. | | `device` | Optional[ComponentDevice] | None | The device on which the model is loaded. If `None`, the default device is automatically selected. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token to download private models from Hugging Face. | | `top_k` | int | 10 | The maximum number of documents to return per query. | | `query_prefix` | str | | A string to add at the beginning of the query text before ranking. Use it to prepend the text with an instruction, as required by reranking models like `bge`. | | `document_prefix` | str | | A string to add at the beginning of each document before ranking. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed with the document. | | `embedding_separator` | str | \n | Separator to concatenate metadata fields to the document. | | `scale_score` | bool | True | If `True`, scales the raw logit predictions using a Sigmoid activation function. | | `score_threshold` | Optional[float] | None | Return documents with a score above this threshold only. | | `trust_remote_code` | bool | False | If `False`, allows only Hugging Face verified model architectures. If `True`, allows custom models and scripts. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `config_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoConfig.from_pretrained` when loading the model configuration. | | `backend` | Literal['torch', 'onnx', 'openvino'] | torch | The backend to use for the Sentence Transformers model. Refer to the [Sentence Transformers documentation](https://sbert.net/docs/sentence_transformer/usage/efficiency.html) for more information. | | `batch_size` | int | 16 | The batch size to use for inference. The higher the batch size, the more memory is required. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `scale_score` | Optional[bool] | None | If `True`, scales the raw logit predictions using a Sigmoid activation function. If set, overrides the value set at initialization. | | `score_threshold` | Optional[float] | None | Return documents only with a score above this threshold. If set, overrides the value set at initialization. | --- ## SleeperGenerator Mock a Generator component for benchmarks and load testing. This component sleeps for a configurable duration and returns a placeholder answer. ## Key Features - Simulates Generator latency without calling an external LLM API. - Sleep duration follows a normal distribution around a configurable mean. - Returns a configurable placeholder answer and metadata. - Useful for pipeline performance testing and benchmarking. ## Configuration 1. Drag the `SleeperGenerator` component onto the canvas from the Component Library. 2. Click the component to open the configuration panel. 3. Set `mean_sleep_in_seconds`, `sleep_scale`, `answer`, and optional `meta` values. ## Connections `SleeperGenerator` accepts a `prompt` string as input. It outputs `replies` — a list containing the placeholder answer — and `meta` — optional metadata. Connect a `PromptBuilder` to the `prompt` input. Connect the `replies` output to `DeepsetAnswerBuilder` or a pipeline output, the same way you would connect a real Generator. ## Usage Examples ### Basic Configuration ```yaml SleeperGenerator: type: deepset_cloud_custom_nodes.generators.sleeper.SleeperGenerator init_parameters: mean_sleep_in_seconds: 5 sleep_scale: 1.0 answer: Placeholder response meta: {} ``` ### Using the Component in a Pipeline This example replaces a real Generator with `SleeperGenerator` for load testing: ```yaml # haystack-pipeline components: sleeper: type: deepset_cloud_custom_nodes.generators.sleeper.SleeperGenerator init_parameters: mean_sleep_in_seconds: 5 sleep_scale: 1.0 answer: Placeholder response meta: {} inputs: prompt: - sleeper.prompt outputs: replies: sleeper.replies ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | prompt | str | | Prompt input. The component does not use this value but accepts it to match the Generator interface. | | generation_kwargs | Optional[Dict[str, Any]] | None | Generation kwargs. The component does not use this value but accepts it to match the Generator interface. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | replies | List[str] | | List containing the placeholder answer. | | meta | List[Dict[str, Any]] | | Metadata returned with the answer. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | mean_sleep_in_seconds | float | 10 | Mean sleep duration in seconds before returning the answer. | | sleep_scale | float | 1.0 | Standard deviation for the sleep duration. | | answer | str | Placeholder | Text returned as the Generator reply. | | meta | Optional[Dict[str, Any]] | None | Metadata returned with the answer. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | prompt | str | | Prompt input. | | generation_kwargs | Optional[Dict[str, Any]] | None | Generation kwargs. | --- ## StringJoiner Join multiple string inputs into a single string output. :::info Work in Progress We're working on adding pipeline examples and most common component connections. ::: ## Key Features - Accepts multiple variadic string inputs and joins them into a single output string. ## Configuration 1. Drag the `StringJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, no configuration is required. ## Connections `StringJoiner` accepts multiple string inputs through its `input_str` variadic input. Connect any component that outputs a string. It outputs the joined string as `output`. Connect it to any downstream component that accepts a string input. ## Source Code To check this component's source code, open [`string_joiner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/joiners/string_joiner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml StringJoiner: type: haystack.components.joiners.string_joiner.StringJoiner init_parameters: {} ``` ```yaml # haystack-pipeline components: StringJoiner: type: haystack.components.joiners.string_joiner.StringJoiner init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `input_str` | Variadic[str] | | The string inputs to join. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `output` | str | | The joined string output. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `input_str` | Variadic[str] | | The string inputs to join. | --- ## StringListJoiner Join multiple lists of strings into a single string output. :::info Work in Progress We're working on adding pipeline examples and most common component connections. ::: ## Key Features - Accepts multiple variadic list-of-string inputs and joins them into a single output string. ## Configuration 1. Drag the `StringListJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, no configuration is required. ## Connections `StringListJoiner` accepts multiple `List[str]` inputs through its `inputs` variadic input. Connect any component that outputs a list of strings. It outputs the joined string as `output`. Connect it to any downstream component that accepts a string input. ## Source Code To check this component's source code, open [`joiner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/testing/sample_components/joiner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml StringListJoiner: type: testing.sample_components.joiner.StringListJoiner init_parameters: {} ``` ```yaml components: StringListJoiner: type: testing.sample_components.joiner.StringListJoiner init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `inputs` | Variadic[List[str]] | | The list of string inputs to join. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `output` | str | | The joined string output. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `inputs` | Variadic[List[str]] | | The list of string inputs to join. | --- ## SuperComponent Wrap an entire pipeline in `SuperComponent` and use it as a single reusable component with simplified inputs and outputs. ## Key Features - Encapsulates a complete pipeline as a single reusable component. - Supports custom input and output name remapping via `input_mapping` and `output_mapping`. - Simplifies complex pipelines by hiding internal complexity. - Useful for defining tools for agents that execute entire pipelines. - Inputs and outputs are dynamically determined by the `input_mapping` and `output_mapping` configurations. ## Configuration 1. Drag the `SuperComponent` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Configure the wrapped `pipeline` by defining all its components and connections in the YAML. - Set `input_mapping` to map external input names to pipeline input socket paths. - Set `output_mapping` to map pipeline output socket paths to external output names. ## Connections Inputs and outputs are dynamically defined based on the `input_mapping` and `output_mapping` configurations. By default, all pipeline inputs are exposed as inputs and all pipeline outputs are exposed as outputs. ## Source Code To check this component's source code, open [`super_component.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/core/super_component/super_component.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml rag_tool: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: query: - bm25_retriever.query - query_embedder.text - ranker.query - prompt_builder.query output_mapping: generator.replies: answer ranker.documents: documents pipeline: components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: index: default max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false create_index: true top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n\nProvided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n\ {{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: max_tokens: 1000 temperature: 0.7 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.messages ``` This is an example RAG pipeline using `SuperComponent` to wrap a retrieval sub-pipeline as a reusable tool: ```yaml # haystack-pipeline components: rag_tool: type: haystack.core.super_component.super_component.SuperComponent init_parameters: input_mapping: query: - bm25_retriever.query - query_embedder.text - ranker.query - prompt_builder.query output_mapping: generator.replies: answer ranker.documents: documents pipeline: components: bm25_retriever: type: haystack_integrations.components.retrievers.opensearch.bm25_retriever.OpenSearchBM25Retriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 fuzziness: 0 query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'default' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: intfloat/simlm-msmarco-reranker top_k: 8 prompt_builder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "You are a helpful assistant answering the user's questions based on the provided documents.\nDo not use your own knowledge.\n\nProvided documents:\n{% for document in documents %}\nDocument [{{ loop.index }}]:\n{{ document.content }}\n{% endfor %}\n\nQuestion: {{ query }}\nAnswer:" generator: type: haystack.components.generators.chat.openai.OpenAIChatGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o generation_kwargs: max_tokens: 1000 temperature: 0.7 connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents - sender: ranker.documents receiver: prompt_builder.documents - sender: prompt_builder.prompt receiver: generator.messages answer_builder: type: deepset_cloud_custom_nodes.augmenters.deepset_answer_builder.DeepsetAnswerBuilder init_parameters: reference_pattern: acm connections: - sender: rag_tool.answer receiver: answer_builder.replies - sender: rag_tool.documents receiver: answer_builder.documents inputs: query: - "rag_tool.query" - "answer_builder.query" outputs: documents: "rag_tool.documents" answers: "answer_builder.answers" max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs Inputs are dynamically defined based on the `input_mapping` configuration. By default, all pipeline inputs are exposed. ### Outputs Outputs are dynamically defined based on the `output_mapping` configuration. By default, all pipeline outputs are exposed. ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `pipeline` | Union[Pipeline, AsyncPipeline] | | The pipeline instance to be wrapped. | | `input_mapping` | Optional[Dict[str, List[str]]] | None | A dictionary mapping component input names to pipeline input socket paths. If not provided, a default mapping is created based on all pipeline inputs. Example: `{"query": ["retriever.query", "prompt_builder.query"]}` | | `output_mapping` | Optional[Dict[str, str]] | None | A dictionary mapping pipeline output socket paths to component output names. If not provided, a default mapping is created based on all pipeline outputs. Example: `{"generator.replies": "replies"}` | ### Run Method Parameters The run method parameters are dynamically determined by the `input_mapping` configuration. Each key in the input mapping becomes a parameter that can be passed at runtime. --- ## TextSplitter Split a text string into a list of strings. :::info Work in Progress We're working on adding pipeline examples and most common component connections. ::: ## Key Features - Accepts a text string as input and splits it into a list of strings. ## Configuration 1. Drag the `TextSplitter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab, no configuration is required. ## Connections `TextSplitter` accepts a `sentence` string as input. Connect it to any component that outputs a string. It outputs a list of strings as `output`. Connect it to any downstream component that accepts a list of strings. ## Source Code To check this component's source code, open [`text_splitter.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/testing/sample_components/text_splitter.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TextSplitter: type: testing.sample_components.text_splitter.TextSplitter init_parameters: {} ``` ```yaml components: TextSplitter: type: testing.sample_components.text_splitter.TextSplitter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `sentence` | str | | The text string to split. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `output` | List[str] | | The list of string segments. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `sentence` | str | | The text string to split. | --- ## TransformersSimilarityRanker Rank documents based on their semantic similarity to the query. :::info Legacy Component This component is considered legacy and will no longer receive updates. It may be deprecated in a future release, with removal following after a deprecation period. Consider using `SentenceTransformersSimilarityRanker` instead, which provides the same functionality along with additional features. ::: ## Key Features - Uses a pre-trained cross-encoder model from Hugging Face to rank documents by semantic similarity to the query. - Configurable number of results returned via `top_k`. - Supports score scaling via Sigmoid activation for normalized similarity scores. - Supports calibration of probabilities via `calibration_factor`. - Supports filtering by score threshold. ## Configuration 1. Drag the `TransformersSimilarityRanker` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the ranking model. Pass a local path or the Hugging Face model name of a cross-encoder model. - Set `top_k` to control how many documents to return. 4. Go to the **Advanced** tab to configure `scale_score`, `calibration_factor`, `score_threshold`, and `batch_size`. ## Connections `TransformersSimilarityRanker` accepts a query string and a list of documents as inputs. Connect it after a retriever or `DocumentJoiner` in a query pipeline. It outputs a ranked list of documents sorted from most to least relevant to the query. Connect its `documents` output to `ChatPromptBuilder`, `AnswerBuilder`, or another downstream component. ## Source Code To check this component's source code, open [`transformers_similarity.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/rankers/transformers_similarity.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: {} ``` ```yaml # haystack-pipeline components: TransformersSimilarityRanker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `scale_score` | Optional[bool] | None | If `True`, scales the raw logit predictions using a Sigmoid activation function. If `False`, disables scaling. | | `calibration_factor` | Optional[float] | None | Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. Used only if `scale_score` is `True`. | | `score_threshold` | Optional[float] | None | Return documents only with a score above this threshold. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents closest to the query, sorted from most similar to least similar. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | Union[str, Path] | cross-encoder/ms-marco-MiniLM-L-6-v2 | The ranking model. Pass a local path or the Hugging Face model name of a cross-encoder model. | | `device` | Optional[ComponentDevice] | None | The device on which the model is loaded. If `None`, overrides the default device. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token to download private models from Hugging Face. | | `top_k` | int | 10 | The maximum number of documents to return per query. | | `query_prefix` | str | | A string to add at the beginning of the query text before ranking. Use it to prepend the text with an instruction, as required by reranking models like `bge`. | | `document_prefix` | str | | A string to add at the beginning of each document before ranking. | | `meta_fields_to_embed` | Optional[List[str]] | None | List of metadata fields to embed with the document. | | `embedding_separator` | str | \n | Separator to concatenate metadata fields to the document. | | `scale_score` | bool | True | If `True`, scales the raw logit predictions using a Sigmoid activation function. | | `calibration_factor` | Optional[float] | 1.0 | Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. Used only if `scale_score` is `True`. | | `score_threshold` | Optional[float] | None | Return documents with a score above this threshold only. | | `model_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoModelForSequenceClassification.from_pretrained` when loading the model. | | `tokenizer_kwargs` | Optional[Dict[str, Any]] | None | Additional keyword arguments for `AutoTokenizer.from_pretrained` when loading the tokenizer. | | `batch_size` | int | 16 | The batch size to use for inference. The higher the batch size, the more memory is required. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `query` | str | | The input query to compare the documents to. | | `documents` | List[Document] | | A list of documents to be ranked. | | `top_k` | Optional[int] | None | The maximum number of documents to return. | | `scale_score` | Optional[bool] | None | If `True`, scales the raw logit predictions using a Sigmoid activation function. If `False`, disables scaling. | | `calibration_factor` | Optional[float] | None | Use this factor to calibrate probabilities with `sigmoid(logits * calibration_factor)`. Used only if `scale_score` is `True`. | | `score_threshold` | Optional[float] | None | Return documents only with a score above this threshold. | --- ## TransformersZeroShotDocumentClassifier Classify documents based on the labels you provide and add the predicted label to the document's metadata. ## Key Features - Uses a Hugging Face zero-shot classification pipeline to classify documents without task-specific training. - Adds the predicted label to the document's `classification` metadata field. - Supports multi-label classification by setting `multi_label=True`. - Runs classification on document `content` by default, or on any metadata field via `classification_field`. - Compatible models include `valhalla/distilbart-mnli-12-3`, `cross-encoder/nli-distilroberta-base`, and `cross-encoder/nli-deberta-v3-xsmall`. ## Configuration 1. Drag the `TransformersZeroShotDocumentClassifier` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the model name or path for zero-shot classification. - Set the `labels` list with the categories to classify documents into, such as `["positive", "negative"]`. 4. Go to the **Advanced** tab to configure `multi_label`, `classification_field`, `device`, and `huggingface_pipeline_kwargs`. ## Connections `TransformersZeroShotDocumentClassifier` accepts a list of documents as input. Connect it to any component that outputs documents, such as `TextFileToDocument`. It outputs a list of documents with the `classification` metadata field added. Connect its `documents` output to `MetadataRouter` to route documents based on their classification, or to `DocumentWriter` for storage. ## Source Code To check this component's source code, open [`zero_shot_document_classifier.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/classifiers/zero_shot_document_classifier.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TransformersZeroShotDocumentClassifier: type: haystack.components.classifiers.zero_shot_document_classifier.TransformersZeroShotDocumentClassifier init_parameters: model: cross-encoder/nli-deberta-v3-xsmall labels: - positive - negative multi_label: false token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false ``` In this index, `TransformersZeroShotDocumentClassifier` classifies documents by sentiment (positive or negative) and sends classified documents to `MetadataRouter`. `MetadataRouter` then routes positive documents to one document store and negative documents to another. ```yaml # haystack-pipeline components: TextFileToDocument: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false TransformersZeroShotDocumentClassifier: type: haystack.components.classifiers.zero_shot_document_classifier.TransformersZeroShotDocumentClassifier init_parameters: model: cross-encoder/nli-deberta-v3-xsmall labels: - positive - negative multi_label: false classification_field: device: token: type: env_var env_vars: - HF_API_TOKEN - HF_TOKEN strict: false huggingface_pipeline_kwargs: MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: positive: operator: OR conditions: - field: classification.label operator: == value: positive negative: operator: OR conditions: - field: classification.label operator: == value: negative DocumentWriter_Positive: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'positive-sentiment-index' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: DocumentWriter_Negative: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: 'negative-sentiment-index' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: # Defines how the components are connected - sender: TextFileToDocument.documents receiver: TransformersZeroShotDocumentClassifier.documents - sender: TransformersZeroShotDocumentClassifier.documents receiver: MetadataRouter.documents - sender: MetadataRouter.positive receiver: DocumentWriter_Positive.documents - sender: MetadataRouter.negative receiver: DocumentWriter_Negative.documents inputs: # Define the inputs for your pipeline files: - TextFileToDocument.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to process. | | `batch_size` | int (Optional) | 1 | Batch size used for processing the content in each document. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents with an added metadata field called `classification`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | | The name or path of a Hugging Face model for zero-shot document classification. | | `labels` | List[str] | | The set of possible class labels to classify each document into, for example, ["positive", "negative"]. The labels depend on the selected model. | | `multi_label` | bool | False | Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered independent and probabilities are normalized for each candidate by doing a softmax of the entailment score vs. the contradiction score. | | `classification_field` | Optional[str] | None | Name of document's meta field to be used for classification. If not set, `Document.content` is used by default. | | `device` | Optional[ComponentDevice] | None | The device on which the model is loaded. If `None`, the default device is automatically selected. If a device/device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The Hugging Face token to use as HTTP bearer authorization. | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | Dictionary containing keyword arguments used to initialize the Hugging Face pipeline for text classification. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | Documents to process. | | `batch_size` | int | 1 | Batch size used for processing the content in each document. | --- ## TransformersZeroShotTextRouter Route text strings to different connections based on a category label. :::info Work in Progress We're working on adding pipeline examples and most common component connections. ::: ## Key Features - Routes text strings to different downstream connections based on zero-shot classification. - Uses a Hugging Face zero-shot classification model to predict the category of the text. - Supports multi-label classification by setting `multi_label=True`. - The set of labels for categorization is configured at initialization time. ## Configuration 1. Drag the `TransformersZeroShotTextRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the `labels` list with the categories to route text to. - Set the model name. The default is `MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33`. 4. Go to the **Advanced** tab to configure `multi_label`, `device`, and `huggingface_pipeline_kwargs`. ## Connections `TransformersZeroShotTextRouter` accepts a `text` string as input. Connect it to any component that outputs a string. It outputs the text to a dynamically created output named after the predicted label. Connect each labeled output to the appropriate downstream component. ## Source Code To check this component's source code, open [`zero_shot_text_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/zero_shot_text_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TransformersZeroShotTextRouter: type: haystack.components.routers.zero_shot_text_router.TransformersZeroShotTextRouter init_parameters: {} ``` ```yaml # haystack-pipeline components: TransformersZeroShotTextRouter: type: haystack.components.routers.zero_shot_text_router.TransformersZeroShotTextRouter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string of text to route. | ### Outputs | Parameter | Type | Default | Description | |-----------|------|---------|-------------| ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `labels` | List[str] | | The set of labels to use for classification. Can be a single label, a string of comma-separated labels, or a list of labels. | | `multi_label` | bool | False | Indicates if multiple labels can be true. If `False`, label scores are normalized so their sum equals 1 for each sequence. If `True`, the labels are considered independent and probabilities are normalized for each candidate by doing a softmax of the entailment score vs. the contradiction score. | | `model` | str | MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33 | The name or path of a Hugging Face model for zero-shot text classification. | | `device` | Optional[ComponentDevice] | None | The device for loading the model. If `None`, automatically selects the default device. If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token used to download private models from Hugging Face. | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments for initializing the Hugging Face zero-shot text classification. | ### Run Method Parameters These are the parameters you can configure for the component's `run()` method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string of text to route. | --- ## Legacy Components A list of components that were removed, replaced, or changed as part of our ongoing work to make pipelines easier to build, maintain, and debug. Use this page to find out what changed and how to update your pipelines. *** These components are hidden in Builder's component library by default, but if you're still using them in your pipelines, they'll continue to work. You can also show them in the library by clicking **More actions** next to the search field and choosing **Show deprecated components**. To learn how to update your pipelines and remove these components, see [Simplify Your Pipelines with Smart Connections](/docs/how-to-guides/designing-your-pipeline/simplify-pipelines.mdx). To access these components in YAML: 1. Go to *Pipelines* and find the pipeline that uses the component. 2. Click **More actions** next to the pipeline and choose *Edit*. The pipeline opens in Builder. 3. In Builder, switch to the YAML editor. ### Joiners As components now accept connections from multiple outputs of the same list type, the following Joiners are no longer necessary: - `DocumentJoiner` - `ListJoiner` For more information, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). ### OutputAdapter With automatic type conversion from `string` to `ChatMessage` and the other way around, you can skip the `OutputAdapter` component in most cases. You'll still need it for: - Converting types that are not supported by automatic type conversion. - Explicit control over formatting or ordering. For details, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). ### DeepsetChatHistoryParser You can now connect the `Agent` directly to `Input`'s `messages` connection. `messages` is augmented with the chat history and the user's query. ### AnswerBuilder You can connect `LLM` or `Agent` directly to `Output`'s `messages` connection, without the helper component `AnswerBuilder`. --- ## AnswerJoiner Use `AnswerJoiner` to merge multiple lists of `Answer` objects from different pipeline branches into a single list. ## Key Features - Merges multiple `Answer` lists from different pipeline branches into one. - Supports concatenation as the join mode. - Optionally limits the number of answers returned with `top_k`. - Optionally sorts answers by score in descending order. ## Configuration 1. Drag the `AnswerJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Join Mode**. The available mode is `concatenate`, which merges all input answer lists into a single list. - Optionally, set **Top K** to limit the number of answers returned. 4. Go to the **Advanced** tab to enable **Sort by Score** if you want answers sorted in descending order by their score. ## Connections `AnswerJoiner` accepts lists of `Answer` objects from multiple components simultaneously. You typically connect it to `AnswerBuilder` components that produce answers from different generators. Its output is a merged `List[AnswerType]` that you connect to the `Output` component. ## Source Code To check this component's source code, open [`answer_joiner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/joiners/answer_joiner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml AnswerJoiner: type: haystack.components.joiners.answer_joiner.AnswerJoiner init_parameters: join_mode: concatenate sort_by_score: false ``` This example shows a pipeline that generates answers from multiple sources and joins them. ```yaml # haystack-pipeline components: PromptBuilder1: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Answer this question briefly: {{ query }}" PromptBuilder2: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Provide a detailed answer to: {{ query }}" Generator1: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini Generator2: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini AnswerBuilder1: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true AnswerBuilder2: type: haystack.components.builders.answer_builder.AnswerBuilder init_parameters: pattern: reference_pattern: last_message_only: false return_only_referenced_documents: true AnswerJoiner: type: haystack.components.joiners.answer_joiner.AnswerJoiner init_parameters: join_mode: concatenate sort_by_score: false connections: - sender: PromptBuilder1.prompt receiver: Generator1.prompt - sender: PromptBuilder2.prompt receiver: Generator2.prompt - sender: Generator1.replies receiver: AnswerBuilder1.replies - sender: Generator2.replies receiver: AnswerBuilder2.replies - sender: AnswerBuilder1.answers receiver: AnswerJoiner.answers - sender: AnswerBuilder2.answers receiver: AnswerJoiner.answers max_runs_per_component: 100 metadata: {} inputs: query: - PromptBuilder1.query - PromptBuilder2.query - AnswerBuilder1.query - AnswerBuilder2.query outputs: answers: AnswerJoiner.answers ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `answers` | Variadic[List[AnswerType]] | Nested list of answers to merge. | | `top_k` | Optional[int] | The maximum number of answers to return. Overrides the instance's `top_k` if provided. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | `answers` | List[AnswerType] | Merged list of answers. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `join_mode` | Union[str, JoinMode] | JoinMode.CONCATENATE | Specifies the join mode to use. Available modes: `concatenate` concatenates multiple lists of answers into a single list. | | `top_k` | Optional[int] | None | The maximum number of answers to return. | | `sort_by_score` | bool | False | If `True`, sorts the answers by score in descending order. If an answer has no score, it is handled as if its score is -infinity. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `answers` | Variadic[List[AnswerType]] | | Nested list of answers to merge. | | `top_k` | Optional[int] | None | The maximum number of answers to return. Overrides the instance's `top_k` if provided. | --- ## BranchJoiner Merge multiple branches of a pipeline into a single output. It receives inputs of the same data type and forwards the first received value to its output. ## Key Features - Merges multiple pipeline branches into a single output. - Type-safe: handles one data type at a time, declared at initialization. - Useful for closing loops and reconciling branches from router components. - Raises an error if more than one value is received in a single run. ## Configuration 1. Drag the `BranchJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Type** to specify the data type the component will receive and pass (for example, `List[ChatMessage]`, `str`, or `List[Document]`). ## Connections `BranchJoiner` typically receives outputs from router components such as `ConditionalRouter` or `TextLanguageRouter`, or from components at the end of parallel branches. Connect each branch's output to `BranchJoiner`'s input, then connect its output to the next component in the pipeline. Common use cases: - **Loop handling:** Close loops in pipelines by merging an error-handling branch back into the main flow. - **Decision-based merging:** Reconcile branches created by router components into a single continuation point. ## Source Code To check this component's source code, open [`branch.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/joiners/branch.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml BranchJoiner: type: haystack.components.joiners.branch.BranchJoiner init_parameters: type_: list[str] ``` ## Connections This example shows a pipeline where `ConditionalRouter` routes queries based on whether they contain a question mark, and `BranchJoiner` consolidates the outputs from different processing approaches. ```yaml # haystack-pipeline components: ConditionalRouter: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: routes: - condition: "{{ '?' in query }}" output: "{{ query }}" output_name: question output_type: str - condition: "{{ '?' not in query }}" output: "{{ query }}" output_name: statement output_type: str QuestionPromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Provide a detailed answer to this question: {{ query }}" StatementPromptBuilder: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: "Acknowledge and expand on this statement: {{ query }}" QuestionGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini generation_kwargs: temperature: 0.3 max_tokens: 500 StatementGenerator: type: haystack.components.generators.openai.OpenAIGenerator init_parameters: api_key: type: env_var env_vars: - OPENAI_API_KEY strict: false model: gpt-4o-mini generation_kwargs: temperature: 0.7 max_tokens: 200 BranchJoiner: type: haystack.components.joiners.branch.BranchJoiner init_parameters: type_: list[str] connections: - sender: ConditionalRouter.question receiver: QuestionPromptBuilder.query - sender: ConditionalRouter.statement receiver: StatementPromptBuilder.query - sender: QuestionPromptBuilder.prompt receiver: QuestionGenerator.prompt - sender: StatementPromptBuilder.prompt receiver: StatementGenerator.prompt - sender: QuestionGenerator.replies receiver: BranchJoiner.value - sender: StatementGenerator.replies receiver: BranchJoiner.value max_runs_per_component: 100 metadata: {} inputs: query: - ConditionalRouter.query outputs: replies: BranchJoiner.value ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `**kwargs` | Any | The input data. Must be of the type declared by `type_` during initialization. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (value) | Declared type | The first value `BranchJoiner` receives from the connected components. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `type_` | Type | | The expected data type of inputs and outputs. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `**kwargs` | Any | | The input data. Must be of the type declared by `type_` during initialization. | --- ## ConditionalRouter Route data to different pipeline branches based on conditions you define using Jinja2 expressions. ## Key Features - Routes data to different outputs based on configurable Jinja2 conditions. - Supports multiple routes, each with its own condition, output, output type, and output name. - Supports custom Jinja2 filters for advanced condition logic. - Supports optional variables that fall back to `None` when not provided at runtime. - Validates route output types when enabled. ## Configuration 1. Drag the `ConditionalRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Define the **Routes**. Each route is a dictionary with four fields: - `condition`: A Jinja2 expression that determines if the route is selected. - `output`: A Jinja2 expression defining the value to pass to the output. - `output_type`: The data type of the output (for example, `str` or `List[int]`). - `output_name`: The name of the output connection used to connect the router to other components. 4. Go to the **Advanced** tab to configure optional settings: - Set **Custom Filters** to add custom Jinja2 filters for use in condition expressions. - Set **Optional Variables** to list variables that should default to `None` when not provided. - Enable **Unsafe** to allow arbitrary code execution in Jinja2 templates (only use with trusted sources). - Enable **Validate Output Type** to raise a `ValueError` if a route output doesn't match its declared type. ## Connections `ConditionalRouter` accepts any variables used in the route conditions as inputs. Connect upstream component outputs to the corresponding input names. Each route produces a named output you can connect to a different downstream component. For example, connect `router.enough_streams` to one component and `router.insufficient_streams` to another. ## Source Code To check this component's source code, open [`conditional_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/conditional_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml ConditionalRouter: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: {} ``` ## Connections ```yaml # haystack-pipeline components: ConditionalRouter: type: haystack.components.routers.conditional_router.ConditionalRouter init_parameters: ``` Here is a Python example that shows how to configure routes and connect the router: ```python from typing import List from haystack import Pipeline from haystack.dataclasses import ByteStream from haystack.components.routers import ConditionalRouter routes = [ { "condition": "{{streams|length > 2}}", "output": "{{streams}}", "output_name": "enough_streams", "output_type": List[ByteStream], }, { "condition": "{{streams|length <= 2}}", "output": "{{streams}}", "output_name": "insufficient_streams", "output_type": List[ByteStream], }, ] pipe = Pipeline() pipe.add_component("router", router) ... pipe.connect("router.enough_streams", "some_component_a.streams") pipe.connect("router.insufficient_streams", "some_component_b.streams_or_some_other_input") ... ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `kwargs` | Any | All variables used in the `condition` expressions in the routes. When used in a pipeline, these variables are passed from the previous component's output. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (dynamic) | Declared output_type | Each route produces a named output corresponding to its `output_name`. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `routes` | List[Route] | | A list of dictionaries, each defining a route. Each route has four fields: `condition` (Jinja2 expression), `output` (Jinja2 expression), `output_type` (data type), and `output_name` (output connection name). | | `custom_filters` | Optional[Dict[str, Callable]] | None | A dictionary of custom Jinja2 filters for use in condition expressions. Keys are filter names, values are callables. | | `unsafe` | bool | False | Enable execution of arbitrary code in Jinja2 templates. Only use this if you trust the source of the template, as it can lead to remote code execution. | | `validate_output_type` | bool | False | Enable validation of route outputs. If a route output doesn't match the declared type, a `ValueError` is raised at runtime. | | `optional_variables` | Optional[List[str]] | None | A list of variable names that are optional in route conditions and outputs. If not provided at runtime, these variables are set to `None`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `kwargs` | Any | | All variables used in the `condition` expressions in the routes. When used in a pipeline, these variables are passed from the previous component's output. | --- ## DeepsetParallelExecutor Run a component in parallel with multiple inputs to process them simultaneously instead of one by one. ## Key Features - Wraps any Haystack component and runs it in parallel across a list of inputs. - Configurable number of parallel workers for throughput tuning. - Supports automatic retries when the wrapped component fails. - Optionally flattens nested output lists for easier downstream processing. - Optionally shows a progress bar during parallel execution. - Can continue processing the remaining inputs if one fails, instead of failing the whole batch. ## Configuration 1. Drag the `DeepsetParallelExecutor` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Component** by specifying the type and init parameters of the component to run in parallel. - Set **Max Workers** to control how many parallel workers to use (default is 4). Set to `1` to disable parallelism. 4. Go to the **Advanced** tab to configure additional settings: - Set **Max Retries** to control how many times to retry a failed component invocation (default is 3). - Enable **Raise on Failure** to raise an exception if any invocation fails after all retries (default is `True`). - Enable **Flatten Output** to flatten nested output lists into a single list (default is `False`). - Enable **Progress Bar** to display a progress bar during execution (default is `False`). ## Connections `DeepsetParallelExecutor` connects to components compatible with the wrapped component's input and output types. Each input must be a list, where each element is one invocation's worth of input for the wrapped component. Outputs are also lists, one result per input. For example, if you wrap a `PromptBuilder`, connect a `List[Document]` as input (one document per invocation) and receive a `List[str]` (one prompt per document). ## Usage Examples ### Basic Configuration ```yaml prompt_builder: type: deepset_cloud_custom_nodes.executors.parallel_executor.DeepsetParallelExecutor init_parameters: max_workers: 1 component: type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Give a short concise context of max 100 words to situate this passage within the overall document for the purposes of improving search retrieval of the passage. Answer only with the concise context and nothing else. document: {{ file.content }} passage: {{ document.content }} context: required_variables: '*' ``` ### Using the Component in an Index This is an example of an index that adds LLM-generated metadata to processed documents. It uses `DeepsetParallelExecutor` to run `PromptBuilder` and generate one prompt per document. It then uses another `DeepsetParallelExecutor` to invoke `AmazonBedrockGenerator` for each prompt. ```yaml # haystack-pipeline components: file_classifier: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - application/pdf - text/markdown - text/html - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - text/csv text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false markdown_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 html_converter: type: haystack.components.converters.html.HTMLToDocument init_parameters: # A dictionary of keyword arguments to customize how you want to extract content from your HTML files. # For the full list of available arguments, see # the [Trafilatura documentation](https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract). extraction_kwargs: output_format: markdown # Extract text from HTML. You can also also choose "txt" target_language: # You can define a language (using the ISO 639-1 format) to discard documents that don't match that language. include_tables: true # If true, includes tables in the output include_links: true # If true, keeps links along with their targets docx_converter: type: haystack.components.converters.docx.DOCXToDocument init_parameters: {} pptx_converter: type: haystack.components.converters.pptx.PPTXToDocument init_parameters: {} xlsx_converter: type: haystack.components.converters.xlsx.XLSXToDocument init_parameters: {} csv_converter: type: haystack.components.converters.csv.CSVToDocument init_parameters: encoding: utf-8 joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false joiner_xlsx: # merge split documents with non-split xlsx documents type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en document_file_adapter: # An Adapter to create a list of corresponding files for split documents. # The result will be of the same size and order as the input documents. # # inputs: # - files: List[Document] before splitting # - documents: List[Document] after splitting # # Outputs: # - output: List[Document] same size as input documents type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: output_type: List[haystack.Document] unsafe: true template: | {%- set file_dict = {} -%} {%- for file in files -%} {%- set _ = file_dict.update({file.meta['file_id']: file}) -%} {%- endfor -%} {%- set files = [] -%} {%- for doc in documents -%} {%- set _ = files.append(file_dict[doc.meta['file_id']]) -%} {%- endfor -%} {{ files }} prompt_builder: # The prompt to create the context # # This template uses DeepsetParallelExecutor to create one prompt per document. # DeepsetParallelExecutor requires each input to be a list of the wrapped component's inputs. # It iterates through the lists and passes each individual inputs to the wrapped component. # Here it receives a list of documents and a list of corresponding files and invokes PromptBuilder for each document-file-pair. # # Component run: PromptBuilder # Component inputs: # - document: Document # - file: Document # # DeepsetParallelExecutor takes a list of each component input: # - document: List[Document] # - file: List[Document] # # Outputs: # - output: List[str] type: deepset_cloud_custom_nodes.executors.parallel_executor.DeepsetParallelExecutor init_parameters: max_workers: 1 # disable parallelism component: # here goes any usual component definition type: haystack.components.builders.prompt_builder.PromptBuilder init_parameters: template: |- Give a short concise context of max 100 words to situate this passage within the overall document for the purposes of improving search retrieval of the passage. Answer only with the concise context and nothing else. document: {{ file.content }} passage: {{ document.content }} context: required_variables: "*" llm: # Runs LLM-based extraction in parallel # # We invoke AmazonBedrockGenerator for each prompt. # For lower latency we run up to 20 requests in parallel. # # Component run in parallel: AmazonBedrockGenerator # Component inputs: # - prompt: str # # DeepsetParallelExecutor takes a list of each component input: # - prompt: List[str] # # Outputs: # - replies: List[str] (note: flatten_output) type: deepset_cloud_custom_nodes.executors.parallel_executor.DeepsetParallelExecutor init_parameters: max_workers: 20 # 20 llm requests in parallel # max_retries: 3 # in case the underlying component does not offer retries itself raise_on_failure: false # don't fail whole batch if one request fails after retry. Failed context will be None. flatten_output: true # ensure we get List[str] instead of List[List[str]] component: type: haystack_integrations.components.generators.amazon_bedrock.generator.AmazonBedrockGenerator init_parameters: model: "us.anthropic.claude-sonnet-4-20250514-v1:0" max_length: 650 model_max_length: 200000 temperature: 0 boto3_config: region_name: us-west-2 read_timeout: 120 retries: total_max_attempts: 3 mode: standard document_meta_updater: # Updates the documents meta data by adding the context. # # We have two list-type inputs (of the same length) and want to process each of their entries together. # Writing a jinja2 template for OutputAdapter that has to deal with (multiple) lists can be challenging. # DeepsetParallelExecutor iterates through the lists using OutputAdapter to add the context to each document's metadata. # As such, the resulting jinja2 code for OutputAdapter becomes trivial. # # Component run in parallel: OutputAdapter # Component inputs: # - context: str # - document: Document # # DeepsetParallelExecutor takes a list of each component input: # - context: List[str] # - document: List[Document] # # Outputs: # - output: List[Document] type: deepset_cloud_custom_nodes.executors.parallel_executor.DeepsetParallelExecutor init_parameters: max_workers: 1 # disable parallelism as this is a cheap operation component: type: haystack.components.converters.output_adapter.OutputAdapter init_parameters: unsafe: true output_type: haystack.Document # sets context to document's meta and returns the document template: | {%- set _ = document.meta.update({'context': context}) -%} {{ document }} document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 normalize_embeddings: true meta_fields_to_embed: - context writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: search_fields: - content - context policy: OVERWRITE connections: # Defines how the components are connected - sender: file_classifier.text/plain receiver: text_converter.sources - sender: file_classifier.application/pdf receiver: pdf_converter.sources - sender: file_classifier.text/markdown receiver: markdown_converter.sources - sender: file_classifier.text/html receiver: html_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.wordprocessingml.document receiver: docx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.presentationml.presentation receiver: pptx_converter.sources - sender: file_classifier.application/vnd.openxmlformats-officedocument.spreadsheetml.sheet receiver: xlsx_converter.sources - sender: file_classifier.text/csv receiver: csv_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents - sender: markdown_converter.documents receiver: joiner.documents - sender: html_converter.documents receiver: joiner.documents - sender: docx_converter.documents receiver: joiner.documents - sender: pptx_converter.documents receiver: joiner.documents - sender: joiner.documents receiver: splitter.documents # pass documents to PromptBuilder - sender: joiner.documents receiver: document_file_adapter.files - sender: splitter.documents receiver: document_file_adapter.documents - sender: document_file_adapter.output receiver: prompt_builder.file - sender: splitter.documents receiver: prompt_builder.document # pass prompts to llm - sender: prompt_builder.prompt receiver: llm.prompt # pass generated context to meta updater - sender: llm.replies receiver: document_meta_updater.context # pass documents to meta updater - sender: splitter.documents receiver: document_meta_updater.document - sender: document_meta_updater.output receiver: joiner_xlsx.documents - sender: xlsx_converter.documents receiver: joiner_xlsx.documents - sender: csv_converter.documents receiver: joiner_xlsx.documents - sender: joiner_xlsx.documents receiver: document_embedder.documents - sender: document_embedder.documents receiver: writer.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - file_classifier.sources max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `kwargs` | Any | The inputs to the component. Each input must be a list of component inputs. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (component outputs) | Dict[str, List[str \| Dict[str, Any]]] | The outputs of the component. Each output is a list. Results are returned in the same order as inputs. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `component` | Component | | The component to run in parallel. Specify the component by type and its init parameters. | | `max_workers` | int | 4 | The maximum number of workers to use in the thread pool executor. | | `max_retries` | int | 3 | The maximum number of retries to attempt if the component fails. | | `progress_bar` | bool | False | Whether to show a progress bar while running the component in parallel. | | `raise_on_failure` | bool | True | Whether to raise an exception if the component fails. | | `flatten_output` | bool | False | Whether to flatten the output of the component. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `kwargs` | Any | | The inputs to the component. Each input must be a list of component inputs. | --- ## DocumentJoiner Merge multiple lists of documents from different pipeline branches into a single list. While most pipelines can use smart connections to automatically merge document lists, `DocumentJoiner` provides explicit control over the joining process. ## Key Features - Merges multiple document lists into a single output. - Maintains document order from input lists. - Supports any number of input connections. - Useful when smart connections don't provide enough control over the merge logic. ## When To Use DocumentJoiner Use `DocumentJoiner` when: - You need explicit control over how document lists are merged. - Your pipeline has complex branching that requires specific joining logic. In most cases, you can simplify your pipeline by using smart connections instead. Components automatically accept multiple lists of the same type and merge them. For more information, see [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections). ## Configuration 1. Drag the `DocumentJoiner` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. The component requires no configuration. Connect multiple components that output document lists to its inputs. ## Connections `DocumentJoiner` accepts `List[Document]` from any number of upstream components, such as retrievers, document processors, or other `DocumentJoiner` components. Its output is a merged `List[Document]` that you can connect to rankers, generators, or document writers. ## Source Code To check this component's source code, open [`document_joiner.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/joiners/document_joiner.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner ``` ```yaml # haystack-pipeline components: bm25_retriever: type: haystack.components.retrievers.in_memory.InMemoryBM25Retriever params: document_store: type: haystack.document_stores.in_memory.InMemoryDocumentStore embedding_retriever: type: haystack.components.retrievers.in_memory.InMemoryEmbeddingRetriever params: document_store: type: haystack.document_stores.in_memory.InMemoryDocumentStore document_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner ranker: type: haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker connections: - sender: bm25_retriever.documents receiver: document_joiner.documents - sender: embedding_retriever.documents receiver: document_joiner.documents - sender: document_joiner.documents receiver: ranker.documents ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `documents` | List[Document] | Lists of documents to join together. Accepts multiple connections. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | `documents` | List[Document] | The combined list of all input documents. | ### Init Parameters `DocumentJoiner` has no initialization parameters. ### Run Method Parameters `DocumentJoiner` has no run-time parameters. ## Related Information - [Logic & Flow Components Overview](/docs/reference/pipeline-components/logic-and-flow-overview.mdx) - [Smart Connections](/docs/concepts/about-pipelines/about-pipelines.mdx#smart-connections) --- ## DocumentLengthRouter Categorize documents based on the length of their `content` field and route them to the appropriate output. ## Key Features - Routes documents to `short_documents` or `long_documents` outputs based on content length. - Configurable character threshold to define what counts as "short". - Routes documents with `None` content to `short_documents` automatically. - Set the threshold to a negative number to route only `None`-content documents to `short_documents`. ## Configuration 1. Drag the `DocumentLengthRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Threshold** to define the maximum number of characters for a document to be considered short. Documents with content length less than or equal to this value (or `None` content) go to `short_documents`. All others go to `long_documents`. The default is `10`. ## Connections `DocumentLengthRouter` receives a `List[Document]` from upstream components such as `DocumentSplitter`. It outputs two streams: - `short_documents`: Documents where `content` is `None` or shorter than or equal to the threshold. Connect this to components that handle short or empty content, such as `LLMDocumentContentExtractor` or `SentenceTransformersDocumentImageEmbedder`. - `long_documents`: Documents with content longer than the threshold. Connect this to standard processing components. ## Source Code To check this component's source code, open [`document_length_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/document_length_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentLengthRouter: type: haystack.components.routers.document_length_router.DocumentLengthRouter init_parameters: threshold: 10 ``` ### Using the Component in a Pipeline This example routes documents to different processing branches based on content length: ```yaml # haystack-pipeline components: splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 500 split_overlap: 50 length_router: type: haystack.components.routers.document_length_router.DocumentLengthRouter init_parameters: threshold: 100 short_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate long_joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate connections: - sender: splitter.documents receiver: length_router.documents - sender: length_router.short_documents receiver: short_joiner.documents - sender: length_router.long_documents receiver: long_joiner.documents inputs: documents: - splitter.documents outputs: short_documents: short_joiner.documents long_documents: long_joiner.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `documents` | List[Document] | A list of documents to categorize based on their content length. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | `short_documents` | List[Document] | Documents where `content` is `None` or whose character count is less than or equal to the threshold. | | `long_documents` | List[Document] | Documents where the character count of `content` is greater than the threshold. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `threshold` | int | 10 | The maximum number of characters for a document to be considered short. Documents where `content` is `None` or whose character count is less than or equal to this value are routed to `short_documents`. All others go to `long_documents`. Set to a negative number to route only `None`-content documents to `short_documents`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents to categorize based on their content length. | --- ## DocumentTypeRouter Route documents to different pipeline branches based on their MIME types. ## Key Features - Routes documents by MIME type to separate output connections. - Supports exact MIME type matching and regex patterns. - Infers MIME types from document metadata or file path metadata. - Routes unclassified documents (no matching MIME type) to a dedicated `unclassified` output. - Supports custom MIME type mappings for uncommon or proprietary file types. ## Configuration 1. Drag the `DocumentTypeRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set **MIME Types** to the list of MIME types or regex patterns to classify documents (for example, `["text/plain", "application/pdf"]`). - Set **MIME Type Meta Field** to the name of the document metadata field that contains the MIME type, if available. - Set **File Path Meta Field** to the name of the document metadata field that contains the file path, if you want the component to infer the MIME type from the file extension. 4. Go to the **Advanced** tab to set **Additional MIME Types**, a dictionary mapping MIME types to file extensions for uncommon or custom file types (for example, `{"application/vnd.custom-type": ".custom"}`). ## Connections `DocumentTypeRouter` receives a `List[Document]` from any upstream component. For each MIME type you specify, it creates a named output connection (for example, `text/plain` or `application/pdf`). Documents that don't match any MIME type go to the `unclassified` output. Connect each named output to the appropriate downstream component, such as a specific converter for that file type. ## Source Code To check this component's source code, open [`document_type_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/document_type_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml DocumentTypeRouter: type: haystack.components.routers.document_type_router.DocumentTypeRouter init_parameters: mime_types: - text/plain - application/pdf ``` ### Using the Component in a Pipeline This index pipeline routes documents to different converters based on MIME type: ```yaml # haystack-pipeline components: type_router: type: haystack.components.routers.document_type_router.DocumentTypeRouter init_parameters: mime_types: - text/plain - application/pdf mime_type_meta_field: mime_type text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 pdf_converter: type: haystack.components.converters.pypdf.PyPDFToDocument init_parameters: {} joiner: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate connections: - sender: type_router.text/plain receiver: text_converter.sources - sender: type_router.application/pdf receiver: pdf_converter.sources - sender: text_converter.documents receiver: joiner.documents - sender: pdf_converter.documents receiver: joiner.documents inputs: documents: - type_router.documents outputs: documents: joiner.documents max_runs_per_component: 100 metadata: {} ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `documents` | List[Document] | A list of documents to categorize based on their MIME type. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | `unclassified` | List[Document] | Documents that don't match any of the specified MIME types. | | `[mime_type]` | List[Document] | Documents matching each specified MIME type (for example, `text/plain` or `application/pdf`). | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `mime_types` | List[str] | | A list of MIME types or regex patterns to classify the input documents (for example, `["text/plain", "audio/x-wav", "image/jpeg"]`). | | `mime_type_meta_field` | Optional[str] | None | The name of the metadata field that holds the MIME type. | | `file_path_meta_field` | Optional[str] | None | The name of the metadata field that holds the file path. Used to infer the MIME type if `mime_type_meta_field` is not provided or missing in a document. | | `additional_mimetypes` | Optional[Dict[str, str]] | None | A dictionary mapping MIME types to file extensions to enhance or override the standard `mimetypes` module. Useful for uncommon or custom file types. For example: `{"application/vnd.custom-type": ".custom"}`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents to categorize based on their MIME type. | --- ## FileTypeRouter Categorize files or byte streams by their MIME types and route them to different pipeline branches. ## Key Features - Routes file paths and `ByteStream` objects to outputs based on MIME type. - Supports exact MIME type matching and regex patterns (for example, `audio/*` or `text/*`). - Infers MIME types from file extensions for file paths and from metadata for byte streams. - Supports custom MIME type mappings for unsupported or proprietary file types. - Optionally raises an error for non-existent files. ## Configuration 1. Drag the `FileTypeRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set **MIME Types** to the list of MIME types or regex patterns to classify the input files or byte streams (for example, `["text/plain", "audio/x-wav", "image/jpeg"]`). 4. Go to the **Advanced** tab to configure optional settings: - Set **Additional MIME Types** to add custom MIME type-to-extension mappings for file types not supported by the standard `mimetypes` module (for example, `{"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}`). - Enable **Raise on Failure** to always raise a `FileNotFoundError` for non-existent files. When disabled (default), this error is only raised when the `meta` parameter is provided at runtime. ## Connections `FileTypeRouter` receives a list of file paths or `ByteStream` objects. For each MIME type you specify, it creates a named output connection. Connect each output to the appropriate file converter (for example, connect the `text/plain` output to `TextFileToDocument` and the `application/pdf` output to a PDF converter). ## Source Code To check this component's source code, open [`file_type_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/file_type_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - audio/x-wav - image/jpeg raise_on_failure: false ``` ```yaml # haystack-pipeline components: FileTypeRouter: type: haystack.components.routers.file_type_router.FileTypeRouter init_parameters: mime_types: - text/plain - audio/x-wav - image/jpeg raise_on_failure: false ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `sources` | List[Union[str, Path, ByteStream]] | A list of file paths or byte streams to categorize. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | Optional metadata to attach to the sources. A single dictionary is applied to all sources; a list must match the number of sources. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (per MIME type) | List[ByteStream] | Files or streams matching each specified MIME type, routed to the corresponding named output. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `mime_types` | List[str] | | A list of MIME types or regex patterns to classify the input files or byte streams (for example, `["text/plain", "audio/x-wav", "image/jpeg"]`). | | `additional_mimetypes` | Optional[Dict[str, str]] | None | A dictionary of MIME type-to-extension mappings to add to the `mimetypes` module. Useful for unsupported or non-native file types (for example, `{"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}`). | | `raise_on_failure` | bool | False | When `True`, `FileNotFoundError` is always raised for non-existent files. When `False`, this error is only raised when the `meta` parameter is provided to `run()`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `sources` | List[Union[str, Path, ByteStream]] | | A list of file paths or byte streams to categorize. | | `meta` | Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] | None | Optional metadata to attach to the sources. A single dictionary is applied to all sources; a list must match the number of sources. | --- ## LLMMessagesRouter Route chat messages to different pipeline branches using a language model for classification. ## Key Features - Uses a language model to classify messages and route them to different outputs. - Works with general-purpose LLMs and specialized moderation models such as Llama Guard. - Routes messages based on configurable output patterns (regular expressions). - Supports a customizable system prompt to adjust the model's classification behavior. ## Configuration 1. Drag the `LLMMessagesRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Chat Generator** to the LLM you want to use for classification. This can be any Haystack chat generator. - Set **Output Names** to the list of output connection names. These names are used to connect the router to other components. - Set **Output Patterns** to the list of regular expressions to match against the LLM's output. Each pattern corresponds to one output name. Patterns are evaluated in order. For moderation models, refer to the model card for the expected output format. 4. Go to the **Advanced** tab to optionally set a **System Prompt** to customize the model's classification behavior. For moderation models, refer to the model card for supported customization. ## Connections `LLMMessagesRouter` receives a list of `ChatMessage` objects (only user and assistant messages are supported). Based on the LLM's classification output, it routes messages to the first output whose pattern matches. Connect each named output to the appropriate downstream component. ## Source Code To check this component's source code, open [`llm_messages_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/llm_messages_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml LLMMessagesRouter: type: haystack.components.routers.llm_messages_router.LLMMessagesRouter init_parameters: {} ``` ```yaml # haystack-pipeline components: LLMMessagesRouter: type: haystack.components.routers.llm_messages_router.LLMMessagesRouter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `messages` | List[ChatMessage] | A list of chat messages to route. Only user and assistant messages are supported. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (per output name) | List[ChatMessage] | Messages routed to the output whose pattern matches the LLM's classification response. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `chat_generator` | ChatGenerator | | A chat generator instance representing the LLM used for classification. | | `output_names` | List[str] | | A list of output connection names used to connect the router to other components. | | `output_patterns` | List[str] | | A list of regular expressions matched against the LLM's output. Each pattern corresponds to one output name. Patterns are evaluated in order. | | `system_prompt` | Optional[str] | None | An optional system prompt to customize the behavior of the LLM. For moderation models, refer to the model card for supported customization options. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `messages` | List[ChatMessage] | | A list of chat messages to route. Only user and assistant messages are supported. | --- ## MetadataRouter Route documents or byte streams to different pipeline branches based on their metadata fields. ## Key Features - Routes documents or byte streams based on metadata filtering rules. - Supports complex conditions using Haystack's metadata filtering syntax (AND, OR, and comparison operators). - Routes unmatched items to a dedicated `unmatched` output. - Can handle both `Document` and `ByteStream` objects in the same configuration. ## Configuration 1. Drag the `MetadataRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set the **Rules** dictionary. Keys are output connection names and values are [metadata filtering expressions](https://docs.haystack.deepset.ai/docs/metadata-filtering). Items matching a rule go to that named output. Items not matching any rule go to `unmatched`. - Set the **Output Type** to `documents` or `byte_streams` depending on what you're routing (default is `documents`). ## Connections `MetadataRouter` receives either a `List[Document]` or a `List[ByteStream]` depending on the configured output type. For each rule you define, it creates a named output connection. Items that don't match any rule go to the `unmatched` output. Connect each named output to the appropriate downstream component. ## Source Code To check this component's source code, open [`metadata_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/metadata_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: output_type: documents rules: edge_1: operator: AND conditions: - field: meta.created_at operator: '>=' value: '2023-01-01' - field: meta.created_at operator: < value: '2023-04-01' ``` ```yaml # haystack-pipeline components: MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: output_type: documents # or byte_streams rules: edge_1: operator: AND conditions: - field: meta.created_at operator: ">=" value: "2023-01-01" - field: meta.created_at operator: "<" value: "2023-04-01" ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `documents` | List[Document] | A list of documents to route. | | `byte_streams` | List[ByteStream] | A list of byte streams to route. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (per rule name) | List[Document] or List[ByteStream] | Items matching the corresponding rule. | | `unmatched` | List[Document] or List[ByteStream] | Items that don't match any rule. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `rules` | Dict[str, Dict] | | A dictionary defining routing rules. Keys are output connection names and values are [metadata filtering expressions](https://docs.haystack.deepset.ai/docs/metadata-filtering). For example: `{"edge_1": {"operator": "AND", "conditions": [{"field": "meta.created_at", "operator": ">=", "value": "2023-01-01"}]}}`. Items not matching any rule go to `unmatched`. | | `output_type` | Optional[str] | documents | The type of objects to route. Can be `documents` or `byte_streams`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `documents` | List[Document] | | A list of documents to route. | | `byte_streams` | List[ByteStream] | | A list of byte streams to route. | --- ## TextLanguageRouter(Logic-and-flow) Route text strings to different pipeline branches based on their detected language. ## Key Features - Detects the language of a text string using `langdetect`. - Routes text to a named output matching the detected language. - Supports multiple languages configured at initialization. - Routes text that doesn't match any configured language to an `unmatched` output. ## Configuration 1. Drag the `TextLanguageRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set **Languages** to the list of ISO 639-1 language codes you want to route (for example, `["en", "de", "fr"]`). If not specified, defaults to `["en"]`. See the supported languages in the [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). ## Connections `TextLanguageRouter` receives a single text string. For each language you configure, it creates a named output connection (for example, `en` or `de`). Text that doesn't match any configured language is routed to the `unmatched` output. Connect each language output to the appropriate downstream component. :::tip Routing Documents by Language To route documents (not text strings) by language, use `DocumentLanguageClassifier` followed by `MetadataRouter`. ::: ## Source Code To check this component's source code, open [`text_language_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/text_language_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TextLanguageRouter: type: haystack.components.routers.text_language_router.TextLanguageRouter init_parameters: {} ``` To route documents by language instead of raw text, use `DocumentLanguageClassifier` followed by `MetadataRouter`. ```yaml # haystack-pipeline components: TextLanguageRouter: type: haystack.components.routers.text_language_router.TextLanguageRouter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `text` | str | A text string to route. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (per language code) | str | The text routed to the output matching the detected language. | | `unmatched` | str | The text when its language doesn't match any configured language. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `languages` | Optional[List[str]] | None | A list of ISO 639-1 language codes. See the supported languages in the [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). If not specified, defaults to `["en"]`. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A text string to route. | --- ## TransformersTextRouter Route text strings to different pipeline branches based on a category label predicted by a Transformers text classification model. ## Key Features - Uses a Hugging Face text classification model to classify input text. - Routes text to a named output matching the predicted label. - Automatically fetches labels from the model configuration if not provided. - Supports private Hugging Face models via API token. - Configurable device placement for GPU or CPU inference. ## Configuration 1. Drag the `TransformersTextRouter` component onto the canvas from the Component Library. 2. Click on the component to open the configuration panel. 3. On the **General** tab: - Set **Model** to the name or path of the Hugging Face text classification model (for example, `cross-encoder/nli-deberta-v3-small`). - Optionally, set **Labels** to the list of classification labels. If not provided, the component fetches the labels from the model's configuration on Hugging Face. 4. Go to the **Advanced** tab to configure optional settings: - Set **Device** to specify the device for loading the model. If not set, the default device is selected automatically. - Set **Token** to provide a Hugging Face API token for downloading private models. Uses the `HF_API_TOKEN` or `HF_TOKEN` environment variable if set to `True`. - Set **Hugging Face Pipeline Kwargs** to pass additional keyword arguments when initializing the Hugging Face text classification pipeline. ## Connections `TransformersTextRouter` receives a single text string. For each label the model can predict, it creates a named output connection. Connect each label output to the appropriate downstream component. The labels are specific to each model. You can find them in the model's description on [Hugging Face](https://huggingface.co/models). ## Source Code To check this component's source code, open [`transformers_text_router.py`](https://github.com/deepset-ai/haystack/blob/main/haystack/components/routers/transformers_text_router.py) in the [Haystack repository](https://github.com/deepset-ai/haystack). ## Usage Examples ### Basic Configuration ```yaml TransformersTextRouter: type: haystack.components.routers.transformers_text_router.TransformersTextRouter init_parameters: {} ``` ```yaml # haystack-pipeline components: TransformersTextRouter: type: haystack.components.routers.transformers_text_router.TransformersTextRouter init_parameters: ``` ## Parameters ### Inputs | Parameter | Type | Description | |-----------|------|-------------| | `text` | str | A string of text to route. | ### Outputs | Parameter | Type | Description | |-----------|------|-------------| | (per label) | str | The text routed to the output matching the predicted label. | ### Init Parameters These are the parameters you can configure in Pipeline Builder: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | str | | The name or path of a Hugging Face model for text classification. | | `labels` | Optional[List[str]] | None | The list of labels. If not provided, the component fetches the labels from the model configuration on Hugging Face using `transformers.AutoConfig.from_pretrained`. | | `device` | Optional[ComponentDevice] | None | The device for loading the model. If `None`, automatically selects the default device. If a device or device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. | | `token` | Optional[Secret] | Secret.from_env_var(['HF_API_TOKEN', 'HF_TOKEN'], strict=False) | The API token for downloading private models from Hugging Face. | | `huggingface_pipeline_kwargs` | Optional[Dict[str, Any]] | None | A dictionary of keyword arguments for initializing the Hugging Face text classification pipeline. | ### Run Method Parameters These are the parameters you can configure for the component's run() method. This means you can pass these parameters at query time through the API, in Playground, or when running a job. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `text` | str | | A string of text to route. | --- ## Logic & Flow Overview # Logic & Flow Components Logic & Flow components help you control how data moves through a pipeline. Use them to route inputs to different branches, run steps in parallel, and join results back together. They are especially useful when you have multiple document types, languages, or output formats and you want your pipeline to adapt without duplicating logic. This group includes routers and joiners for common branching patterns. For example, you can route based on metadata, language, file type, document type, or length, then merge results from different branches into a single output. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## Pipeline Components(Pipeline-components) # Pipeline Components Overview Components are the fundamental building blocks of your pipelines, dictating the flow of data. Each component performs a designated task on the data and then forwards the results to subsequent components. *** ## How Components Work Components receive predefined inputs within the pipeline, execute a specific function, and produce outputs. For example, a component may take files, convert them into embeddings, and pass these embeddings on to the next connected component. You have the flexibility to mix, match, and interchange components in your pipelines. Components are often powered by language models, like LLMs or transformer models, to perform their tasks. ## Connecting Components: Inputs and Outputs Components accept specific inputs and produce defined outputs. To connect components in a pipeline, you must know the types of inputs and outputs they accept. The output type from one component must be compatible with the input type of the subsequent one. For example, to connect a retriever and a ranker in a pipeline, you must know that the retriever outputs `List[Document]` and the ranker accepts `List[Document]` as input. When creating a pipeline in Pipeline Builder, you can click the connector to see the list of popular and compatible connections: To connect components, click a connection point on one component, then on the other, and you'll see a line formed from one component's output to the other component's input. When working in YAML, you indicate their output and input names, for example: ```yaml # ... connections: - sender: retriever.documents receiver: ranker.documents # ... ``` The output of the sender component can have a different name than the input of the receiver component as long as their types match, as in this example: ```yaml # ... connections: - sender: file_type_router.text/plain receiver: text_converter.sources # ... ``` A component must always receive all of its required inputs. Typically, a component's input can connect to only one output. But, if a component's input type is `variadic`, it can receive multiple outputs. For detailed specifications on what inputs and outputs each component requires and generates, refer to the individual documentation pages for each component. The component's inputs and outputs are listed at the top of the page: ## Configuring Components ### In Pipeline Builder In Pipeline Builder, you simply drag components onto the canvas from the component library. You can then customize the component's parameters on the component card: You can change the component name by clicking it and typing in a new name. And that's it! ### In YAML When adding a component to the pipeline YAML configuration, you must add the following information: - _Component name_: This is a custom name you give to a component. You then use this name when configuring the component's connections. - _Type_: Each component has a type you must add to the YAML. You can check the component's type on the component's documentation page: - _Init_parameters_: These are the configuration parameters for the component. You can check them on the component's documentation page or in the API reference. To leave the default values, add an empty dictionary: `init_parameters: {}`. This is an example of how you can configure a component in the YAML: ```yaml components: my_component: # this is a custom name type: haystack.components.routers.file_type_router.FileTypeRouter # this is the component type you can find in component's documentation init_parameters: {} # this uses the default parameter values another_component: type: haystack.components.joiners.document_joiner.DocumentJoiner init_parameters: join_mode: concatenate sort_by_score: false ``` ### Connecting Components As components can have multiple outputs, you must explicitly indicate the component's output you want to send to another component. You configure how components connect in the `connections` section of the YAML, specifying the custom names of the components and the names of their output and input you want to connect, as in this example: ```yaml connections: # we're connecting the text/plain output of the sender to the sources input of the receiver component - sender: my_component.text/plain receiver: text_converter.sources ``` If a component accepts outputs from multiple components, you explicitly define each connection, as in this example: ```yaml connections: - sender: embedding_retriever.documents receiver: joiner.documents - sender: bm25_retriever.documents. receiver: joiner.documents ``` ## Component Groups Components are grouped by their function, for example, embedders, generators, and so on. Read about what the groups do to help you find appropriate components. :::tip GPU Acceleration By default, components run on CPU. You can turn on GPU acceleration in the pipeline or index settings to speed up processing. For details, see [GPU Acceleration](/docs/enable-gpu-acceleration). ::: ### Embedders Embedders convert text strings or `Document` objects into vector representations (embeddings). They use pre-trained models to do that. Embeddings are vector representations of text that capture the context and meaning of words, rather than just relying on keywords. In LLM apps, they speed up processing and improve the model's ability to understand complex linguistic nuances and semantic understanding of text. #### Text and Document Embedders There are two types of embedders: text and document. Text embedders work with text strings and are most often used at the beginning of query pipelines to convert query text into vectors and send it to a retriever. Document embedders embed Document objects and are most often used in indexing pipelines, after converters, and before DocumentWriter. You must use the same embedding model for text and documents. This means that if you use `CohereDocumentEmbedder` in your indexing pipeline, you must then use `CohereTextEmbedder` with the same model in your query pipeline. ### Generators Generators let you use large language models (LLMs) in your applications. Each model provider has a dedicated Generator. There are also ChatGenerators designed for chat-based interactions. Learn when to use each type and how they differ. #### Choosing a Generator Each model provider or model-hosting platform supported by has a dedicated Generator. Choose the one that works with the model provider you want to use. For example, to use the Claude model through Anthropic's API, choose `AnthropicGenerator`. To use models through Amazon Bedrock, choose `AmazonBedrockGenerator`. For guidance on models, see [Language Models in Haystack Enterprise Platform](/docs/concepts/language-models-in-deepset-cloud.mdx). #### Generators and ChatGenerators Most Generators have a corresponding ChatGenerator. - Generators are designed for text-generation tasks, such as in a retrieval augmented generation (RAG) system, where the user asks a question and receives a one-time answer. - ChatGenerators handle multi-turn conversations, maintaining context and consistency throughout the interaction. They also support tool calling, which allows the model to make calls to external tools or functions. #### Key Differences | | Generators | ChatGenerators | |---|---|---| | **Input type** | String (supports Jinja2 syntax) | List of `ChatMessage` objects | | **Output type** | Text | `ChatMessage` | | **Best for** | • Single-turn text generation• RAG-style Q&A | • Multi-turn chat scenarios• Maintaining context across interactions• Assuming a consistent role• Tool calls• Using various content types, such as text and images, in prompts | | **Tool calling** | Not supported | Supported (accepts tools and functions as parameters) | | **Used with** | `PromptBuilder` | `ChatPromptBuilder` | #### When to Use Each - Use a ChatGenerator if: - Your application involves multi-turn conversations. - The model needs to call external tools or functions. - You want to use various content types in the prompt, for example images and text. - Use a Generator if the model only needs to generate answers without maintaining conversation history. ### ChatMessage `ChatMessage` is a data class in Haystack used by ChatGenerators and `ChatPromptBuilder`. `ChatPromptBuilder` sends a list of `ChatMessages` to a ChatGenerator, which then also returns a list of `ChatMessages`. Each message has a role (such as system, user, assistant, or tool) and associated content. The system message is used to set the overall tone and instructions for the conversation, for example: "You are a helpful assistant." The user message is the input from the user, usually a query, but it can also include documents to pass to the model. During the interaction, the LLM generates the next message in the conversation, usually as an assistant. For details on the message format and its properties, see [ChatMessage in Haystack documentation](https://docs.haystack.deepset.ai/docs/chatmessage). When using `ChatPromptBuilder` always provide your instructions using the `template` parameter in the following format: In most cases, you'll write your instructions using the `text` content type and roles such as `user`, `system`, `assistant`, or `tool`. For instance, you might include the model's instructions as a `system` role `ChatMessage`, and the user's input as a `user` role `ChatMessage`. In the following example, we include retrieved documents within the user message together with the query: ```yaml - _content: - text: | You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. _role: system - _content: - text: | Question: {{ query }} _role: user ``` If the LLM calls a tool, it outputs a message with the content type `tool_call`. You can use this content type to configure conditional pipeline paths. For example, you can create two routes with `ConditionalRouter`: one route for when the LLM makes a tool call, and another for when it doesn't. #### Jinja2 Syntax in ChatPromptBuilders You can pass ChatMessages as Jinja2 strings in the `template` parameter of `ChatPromptBuilder`. This makes it possible to create structured ChatMessages with mixed content types, such as images and text. It also makes it possible to test the prompt in Prompt Explorer. Use the `{% message %}` tag to include the `ChatMessage` in the prompt. For example: ```text {% message role="system" %} You are a helpful assistant answering the user's questions. If the answer is not in the documents, rely on the web_search tool to find information. Do not use your own knowledge. {% endmessage %} ``` For details, see [ChatPromptBuilder](/docs/reference/pipeline-components/legacy-components/ChatPromptBuilder.mdx) and [Writing Prompts in Haystack Enterprise Platform](/docs/how-to-guides/designing-your-pipeline/work-with-llms/write-prompts-in-deepset-cloud.mdx). #### Generators in a Pipeline - Generators receive the prompt from `PromptBuilder` and return a list of strings. They can easily connect to any component that accepts a list of strings as input. - ChatGenerators receive prompts from `ChatPromptBuilder` in the form of a list of `ChatMessage` objects or templatized Jinja2 strings and they return a list of `ChatMessage` objects. - If you want a ChatGenerator's output to be the final pipeline output, you can either connect it directly to `AnswerBuilder` or use an `OutputAdapter` to convert the ChatGenerator's output into a list of strings and then connect it to `DeepsetAnswerBuilder`. For details, see [Common Component Combinations](/docs/reference/pipeline-components/common-component-combinations.mdx). ### Limitations ChatGenerators work in Prompt Explorer only if you use the Jinja2 syntax in their `template` parameter. If you use ChatMessages, you experiment with prompts using the Configurations feature in the Playground and modify the ChatPromptBuilder's `template` parameter. For details, see [Modify Pipeline Parameters at Query Time](/docs/how-to-guides/searching-with-your-pipeline/set-runtime-parameters-to-override-pipeline-configuration.mdx). ## Haystack Components Haystack is 's open source Python framework for building production-ready AI-based systems. is based on Haystack and uses its components, pipelines, and methods under the hood. To learn more about Haystack, see the [Haystack website](https://haystack.deepset.ai/). ### External Links combines Haystack components with its own unique components. The -specific components are fully documented on this website. For Haystack components, we provide direct links to the official Haystack documentation. To help you differentiate, Haystack components are marked with an arrow icon in the navigation. Clicking on these components will take you to the Haystack documentation page. ### Using Haystack Components Documentation In Haystack, you can run some components on their own. You can see examples of this in the _Usage_ section of each component page. In , you can only use components in pipelines. To see usage examples, check the _Usage>In a pipeline_ section. You can also check the component's code in the [Haystack repository](https://github.com/deepset-ai/haystack). The path to the component is always available at the top of the component documentation page. --- ## Your Custom Components This section contains all your saved custom components, grouped by scope, and the `Code` component. ## Available Components {useCurrentSidebarCategory().items.map((item) => ( {'href' in item ? {item.label} : item.label} ))} --- ## Test Just click delete. It's simple. --- ## Tutorial: Building a Deal Desk Agent with Search and Custom Code Build an agent that helps a sales team decide whether a discount on a B2B deal can be approved. The agent uses two tools: a document search pipeline that finds the right pricing policy excerpts, and a custom code tool that applies your discount rules with exact thresholds. *** - **Level**: Intermediate - **Time to complete**: 20 minutes - **Prerequisites**: - A workspace where you'll build the agent. - An LLM connection configured in your workspace. To learn how to set up an LLM connection, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). - Basic knowledge of [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and the [Agent](/docs/reference/pipeline-components/ai/Agent.mdx) component. - **Goal**: After completing this tutorial, you will have a working agent that searches deal desk policy documents and checks discount approval with deterministic business rules. *** ## What You're Building An agent that supports sales teams in deciding whether they can grant a discount on a deal based on the company's pricing policy. Account executives ask the deal desk questions like: > "A healthcare prospect wants 28% off a $95,000 annual contract. Can I approve this myself?" To answer correctly, the agent needs to know two things: 1. Policy context: What do the company's pricing guidelines say about healthcare caps, enterprise thresholds, and escalation? 2. Who makes the final decision: Is this discount within rep authority, or does it need a manager or VP? An LLM can summarize policy text, but it should not guess discount limits or approval tiers. That is what custom code is for. The agent will have two tools: 1. `search_deal_policy` — A document search pipeline that retrieves relevant deal desk and pricing policy snippets. It works on your own files. 2. `check_discount_approval` — A custom Python function that takes deal facts (ACV, discount percent, contract term, vertical) and returns a structured approval result. The function is configured with fixed thresholds (rep limit, manager limit, VP limit) that you set once in the tool card. The agent extracts the deal facts from the sales rep's message and passes them to the tool at runtime. Search finds the policy language to cite. Code applies the rules the same way every time. The agent combines both into a clear answer for the sales rep. *** ## Upload Sample Files Upload a small deal desk policy corpus. You can use your own documents, or use the sample files prepared for this tutorial. 1. Download the four files from the [`GDrive folder`](https://drive.google.com/drive/folders/1wer4p3YghXxkFyJK59VwFtqOrtEo9wZ5?usp=sharing). 2. In , switch to the workspace where you want to build the agent and go to *Files > Upload Files*. 3. Choose the files you downloaded and click **Upload**. Wait until the files are uploaded to the workspace. **Result**: Your workspace contains four Atlas Analytics policy documents: | File | What it represents | | --- | --- | | `deal-desk-discount-policy.md` | Rep, manager, and VP discount authority | | `enterprise-pricing-guidelines.md` | List price bands and packaging tiers | | `healthcare-vertical-rules.md` | Extra caps and approvals for healthcare deals | | `approval-escalation-matrix.md` | Who must approve which discount scenarios | ## Create an Index Index the files so the agent can search them. 1. Go to *Indexes > Create Index*. 2. Choose **Standard Index (English)** and click **Create Index**. 3. Leave the default index configuration and click **Enable**. Wait until indexing finishes. **Result**: Your files are indexed and ready for search. The *Standard Index (English)* index has status *indexed*. ## Create the Agent 1. In , open the workspace where your index lives and go to **Pipelines > Create Pipeline**. 2. On the Templates page, click **Create empty pipeline**. 3. Enter *deal-desk-agent* as the pipeline name and click **Create Pipeline**. 4. In Builder, click **Add** to open the component library and add the following components: - `Input` - `Agent` - `Output` 5. Connect `Input` to the `Agent` and `Agent` to `Output`. 6. Click **Model** on the `Agent` component and choose the model you want to use for the agent. **Result**: You have created a minimal agent. Next you will add the two tools and the system prompt. ## Create the Deal Policy Search Pipeline Create the first tool: a document search pipeline over your deal desk policies. 1. Leave Builder and go to **Pipeline Templates**. 2. Choose **Document Search** as the category, find **Semantic Document Search**, and click **Use Template**. 3. Enter *deal-policy-search* as the pipeline name and click **Create Pipeline**. 4. Click the `OpenSearchDocumentStore` component to open its configuration and in the Index field,choose the *Standard Index (English)* index. 5. Test the pipeline: click **Run Pipeline** next to the `Input` component and type `healthcare discount cap`. You should see retrieved policy snippets. 6. Click **Deploy** to make the pipeline available to the agent as a tool. Confirm you're deploying the latest version and click **Deploy**.
Pipeline YAML This is the YAML configuration for the document search pipeline: ```yaml components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: Standard-Index-English top_k: 20 # The number of results to return ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents inputs: query: - query_embedder.text - ranker.query filters: - embedding_retriever.filters outputs: documents: ranker.documents ```
**Result**: You have a document search pipeline that returns relevant policy snippets and is ready to be used as a tool. ## Add the Deal Policy Search Tool to the Agent Attach the search pipeline as a tool on your agent: 1. Leave Builder and on the Pipelines page click the *deal-desk-agent* pipeline to open it. 2. Click the `Agent` component to open its configuration. 3. In the *Tools* section, click **Add Tool**. 4. Choose *Pipeline* as the tool type. 5. On the Create Pipeline Tool window, choose *Existing pipeline* and select *deal-policy-search*. 6. Leave *Current draft* as the pipeline version. 7. Enter `search_deal_policy` as the tool name. 8. Copy the following text and paste it as the tool description: ```text Search Atlas Analytics deal desk policies for discount authority, pricing tiers, vertical rules, and approval escalation. Use when you need policy language to cite in a discount approval answer. ``` 9. Click **Add Pipeline Tool**. **Result**: The agent has a pipeline tool that can search deal desk policies. :::info When you add an existing pipeline as a tool, the platform handles input and output mapping for you. For details, see [Add a Pipeline as a Tool](/docs/how-to-guides/building-agents/configuring-agent.mdx#add-a-pipeline-as-a-tool). ::: ## Add the Discount Approval Code Tool The second tool encodes the company's discount approval rules in Python. The code uses a class with `__init__` parameters for the fixed thresholds and a `@tool` function the agent calls with per-deal facts from the conversation. :::tip Init parameters vs tool parameters `__init__` parameters are configured once in the tool card UI — they're the business rules that rarely change (discount caps, ACV thresholds). `@tool` function arguments are what the agent passes at runtime from the sales rep's message (contract value, discount percent, term, vertical). To create a second pipeline with different thresholds for a different market, you clone it and change only the init parameters. ::: 1. On the `Agent` componentconfiguration, in the *Tools* section, click **Add Tool**. 2. Choose **Code** as the tool type. 3. Type `check_discount_approval` as the tool name. 4. Copy the following text and paste it as the tool description: ```text Check whether a requested discount needs rep, manager, or VP approval given ACV, discount percent, contract term, and vertical. ``` :::note Keep the description on a single line. Some LLM providers, including Anthropic, reject tool descriptions that contain line breaks. ::: 5. Click **Create Tool**. 6. In the code editor, paste the following code replacing the example code: ```python from typing import Annotated from haystack.tools import tool class DiscountApprovalEngine: """Discount rules configured at deploy time through init parameters.""" def __init__( self, max_rep_discount_percent: float = 15, manager_max_discount_percent: float = 25, vp_approval_acv_threshold_usd: float = 75000, healthcare_max_without_vp: float = 20, multi_year_bonus_percent: float = 3, ): self.max_rep_discount_percent = max_rep_discount_percent self.manager_max_discount_percent = manager_max_discount_percent self.vp_approval_acv_threshold_usd = vp_approval_acv_threshold_usd self.healthcare_max_without_vp = healthcare_max_without_vp self.multi_year_bonus_percent = multi_year_bonus_percent def check( self, annual_contract_value_usd: float, requested_discount_percent: float, contract_term_years: int, industry_vertical: str, ) -> dict: vertical = industry_vertical.strip().lower() healthcare_verticals = {"healthcare", "life_sciences", "life sciences", "pharma"} rep_limit = self.max_rep_discount_percent if contract_term_years >= 2: rep_limit += self.multi_year_bonus_percent if vertical in healthcare_verticals and requested_discount_percent > self.healthcare_max_without_vp: return { "rep_can_approve": False, "approval_required": "vp_sales", "rep_discount_limit_percent": rep_limit, "reason": ( f"Healthcare vertical discounts above {self.healthcare_max_without_vp}% " "require VP Sales approval." ), } if ( annual_contract_value_usd > self.vp_approval_acv_threshold_usd and requested_discount_percent > self.max_rep_discount_percent ): return { "rep_can_approve": False, "approval_required": "vp_sales", "rep_discount_limit_percent": rep_limit, "reason": ( f"Deals over ${self.vp_approval_acv_threshold_usd:,.0f} with a discount " f"above {self.max_rep_discount_percent}% require VP Sales approval." ), } if requested_discount_percent <= rep_limit: return { "rep_can_approve": True, "approval_required": "none", "rep_discount_limit_percent": rep_limit, "reason": ( f"Requested discount is within the rep limit of {rep_limit}% " f"({'includes multi-year bonus' if contract_term_years >= 2 else 'standard authority'})." ), } if requested_discount_percent <= self.manager_max_discount_percent: return { "rep_can_approve": False, "approval_required": "sales_manager", "rep_discount_limit_percent": rep_limit, "reason": ( f"Discount exceeds rep limit of {rep_limit}% but is within the " f"{self.manager_max_discount_percent}% manager threshold." ), } return { "rep_can_approve": False, "approval_required": "vp_sales", "rep_discount_limit_percent": rep_limit, "reason": ( f"Discount above {self.manager_max_discount_percent}% requires VP Sales approval." ), } _engine = DiscountApprovalEngine() @tool def check_discount_approval( annual_contract_value_usd: Annotated[float, "Annual contract value in USD"], requested_discount_percent: Annotated[float, "Requested discount as a percentage, for example 28 for 28%"], contract_term_years: Annotated[int, "Contract length in years"], industry_vertical: Annotated[ str, "Industry vertical, for example healthcare, financial_services, or standard", ], ): """Check discount approval level using Atlas Analytics deal desk rules.""" acv = float(str(annual_contract_value_usd).replace(",", "")) discount = float(str(requested_discount_percent).replace("%", "").strip()) term = int(str(contract_term_years).strip()) return _engine.check( annual_contract_value_usd=acv, requested_discount_percent=discount, contract_term_years=term, industry_vertical=industry_vertical, ) ``` 7. Close the code editor. **Result**: The agent has a code tool that returns a structured approval result for any deal the sales rep describes. ## Set the System Prompt Give the agent instructions so it knows when to use each tool. 1. Click the **Agent** component to open its configuration. 2. Copy the following text and paste it as the system prompt: ```text You are an Atlas Analytics deal desk assistant helping sales reps evaluate discount requests. You have access to two tools: 1. search_deal_policy: Search deal desk policies for discount authority, pricing tiers, vertical rules, and approval escalation. 2. check_discount_approval: Check whether a discount can be approved at rep level or needs escalation. Pass annual_contract_value_usd, requested_discount_percent, contract_term_years, and industry_vertical. Workflow: - Extract deal facts from the user's message (ACV, discount, contract term, vertical). - If any fact is missing, ask one short follow-up question. - Call check_discount_approval with the extracted facts. - Call search_deal_policy to find policy excerpts that support your answer. - Combine the approval result with policy citations in your reply. Response format: - Can the rep approve: yes or no - Approval required: none, sales_manager, or vp_sales - Rep discount limit - Policy references from search_deal_policy - Next steps for the sales rep ```
Full AgentYAML Configuration This is the YAML configuration for the agent with tools: ```yaml inputs: query: [] filters: [] files: [] messages: - Agent.messages components: Agent: type: haystack.components.agents.agent.Agent init_parameters: chat_generator: type: haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator init_parameters: model: claude-sonnet-4-6 ignore_tools_thinking_messages: true api_key: type: env_var strict: true env_vars: - ANTHROPIC_API_KEY tools: - type: haystack.tools.pipeline_tool.PipelineTool data: name: search_deal_policy description: >- Search Atlas Analytics deal desk policies for discount authority, pricing tiers, vertical rules, and approval escalation. Use when you need policy language to cite in a discount approval answer. input_mapping: query: - query_embedder.text - ranker.query filters: - embedding_retriever.filters output_mapping: ranker.documents: documents pipeline: components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: embedding_dim: 768 index: Standard-Index-English top_k: 20 ranker: type: deepset_cloud_custom_nodes.rankers.nvidia.ranker.DeepsetNvidiaRanker init_parameters: model: tomaarsen/Qwen3-Reranker-0.6B-seq-cls top_k: 20 connections: - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: ranker.documents is_pipeline_async: false inputs_from_state: {} outputs_to_string: {} outputs_to_state: {} _meta: name: search_deal_policy description: >- Search Atlas Analytics deal desk policies for discount authority, pricing tiers, vertical rules, and approval escalation. Use when you need policy language to cite in a discount approval answer. tool_id: pipeline_version_id: c9bdb695-fa2e-47c7-a25a-3bccc9701817 - type: deepset_cloud_custom_nodes.tools.code_tool.CodeTool data: name: check_discount_approval description: Check whether a requested discount needs rep, manager, or VP approval given ACV, discount percent, contract term, and vertical. code: "from typing import Annotated\r \r from haystack.tools import tool\r \r \r class DiscountApprovalEngine:\r \ \"\"\"Discount rules configured at deploy time through init parameters.\"\"\"\r \r \ def __init__(\r \ self,\r \ max_rep_discount_percent: float = 15,\r \ manager_max_discount_percent: float = 25,\r \ vp_approval_acv_threshold_usd: float = 75000,\r \ healthcare_max_without_vp: float = 20,\r \ multi_year_bonus_percent: float = 3,\r \ ):\r \ self.max_rep_discount_percent = max_rep_discount_percent\r \ self.manager_max_discount_percent = manager_max_discount_percent\r \ self.vp_approval_acv_threshold_usd = vp_approval_acv_threshold_usd\r \ self.healthcare_max_without_vp = healthcare_max_without_vp\r \ self.multi_year_bonus_percent = multi_year_bonus_percent\r \r \ def check(\r \ self,\r \ annual_contract_value_usd: float,\r \ requested_discount_percent: float,\r \ contract_term_years: int,\r \ industry_vertical: str,\r \ ) -> dict:\r \ vertical = industry_vertical.strip().lower()\r \ healthcare_verticals = {\"healthcare\", \"life_sciences\", \"life sciences\", \"pharma\"}\r \r \ rep_limit = self.max_rep_discount_percent\r \ if contract_term_years >= 2:\r \ rep_limit += self.multi_year_bonus_percent\r \r \ if vertical in healthcare_verticals and requested_discount_percent > self.healthcare_max_without_vp:\r \ return {\r \ \"rep_can_approve\": False,\r \ \"approval_required\": \"vp_sales\",\r \ \"rep_discount_limit_percent\": rep_limit,\r \ \"reason\": (\r \ f\"Healthcare vertical discounts above {self.healthcare_max_without_vp}% \"\r \ \"require VP Sales approval.\"\r \ ),\r \ }\r \r \ if (\r \ annual_contract_value_usd > self.vp_approval_acv_threshold_usd\r \ and requested_discount_percent > self.max_rep_discount_percent\r \ ):\r \ return {\r \ \"rep_can_approve\": False,\r \ \"approval_required\": \"vp_sales\",\r \ \"rep_discount_limit_percent\": rep_limit,\r \ \"reason\": (\r \ f\"Deals over ${self.vp_approval_acv_threshold_usd:,.0f} with a discount \"\r \ f\"above {self.max_rep_discount_percent}% require VP Sales approval.\"\r \ ),\r \ }\r \r \ if requested_discount_percent <= rep_limit:\r \ return {\r \ \"rep_can_approve\": True,\r \ \"approval_required\": \"none\",\r \ \"rep_discount_limit_percent\": rep_limit,\r \ \"reason\": (\r \ f\"Requested discount is within the rep limit of {rep_limit}% \"\r \ f\"({'includes multi-year bonus' if contract_term_years >= 2 else 'standard authority'}).\"\r \ ),\r \ }\r \r \ if requested_discount_percent <= self.manager_max_discount_percent:\r \ return {\r \ \"rep_can_approve\": False,\r \ \"approval_required\": \"sales_manager\",\r \ \"rep_discount_limit_percent\": rep_limit,\r \ \"reason\": (\r \ f\"Discount exceeds rep limit of {rep_limit}% but is within the \"\r \ f\"{self.manager_max_discount_percent}% manager threshold.\"\r \ ),\r \ }\r \r \ return {\r \ \"rep_can_approve\": False,\r \ \"approval_required\": \"vp_sales\",\r \ \"rep_discount_limit_percent\": rep_limit,\r \ \"reason\": (\r \ f\"Discount above {self.manager_max_discount_percent}% requires VP Sales approval.\"\r \ ),\r \ }\r \r \r _engine = DiscountApprovalEngine()\r \r \r @tool\r def check_discount_approval(\r \ annual_contract_value_usd: Annotated[float, \"Annual contract value in USD\"],\r \ requested_discount_percent: Annotated[float, \"Requested discount as a percentage, for example 28 for 28%\"],\r \ contract_term_years: Annotated[int, \"Contract length in years\"],\r \ industry_vertical: Annotated[\r \ str,\r \ \"Industry vertical, for example healthcare, financial_services, or standard\",\r \ ],\r ):\r \ \"\"\"Check discount approval level using Atlas Analytics deal desk rules.\"\"\"\r \ acv = float(str(annual_contract_value_usd).replace(\",\", \"\"))\r \ discount = float(str(requested_discount_percent).replace(\"%\", \"\").strip())\r \ term = int(str(contract_term_years).strip())\r \ return _engine.check(\r \ annual_contract_value_usd=acv,\r \ requested_discount_percent=discount,\r \ contract_term_years=term,\r \ industry_vertical=industry_vertical,\r \ )" _meta: name: check_discount_approval description: tool_id: system_prompt: >- {% message role="system" %} You are an Atlas Analytics deal desk assistant helping sales reps evaluate discount requests. You have access to two tools: 1. search_deal_policy: Search deal desk policies for discount authority, pricing tiers, vertical rules, and approval escalation. 2. check_discount_approval: Check whether a discount can be approved at rep level or needs escalation. Pass annual_contract_value_usd, requested_discount_percent, contract_term_years, and industry_vertical. Workflow: - Extract deal facts from the user's message (ACV, discount, contract term, vertical). - If any fact is missing, ask one short follow-up question. - Call check_discount_approval with the extracted facts. - Call search_deal_policy to find policy excerpts that support your answer. - Combine the approval result with policy citations in your reply. Response format: - Can the rep approve: yes or no - Approval required: none, sales_manager, or vp_sales - Rep discount limit - Policy references from search_deal_policy - Next steps for the sales rep {% endmessage %} user_prompt: required_variables: exit_conditions: state_schema: {} max_agent_steps: 100 streaming_callback: raise_on_tool_invocation_failure: false tool_invoker_kwargs: confirmation_strategies: outputs: answers: documents: messages: Agent.messages ```
**Result**: The agent has a clear policy for when and how to use each tool. ## Test the Agent 1. In Builder, with the deal-desk-agent pipeline open, click **Run Pipeline** next to the **Input** component. 2. Paste a message like this: ```text A healthcare prospect wants 28% off a $95,000 annual contract on a 1-year deal. Can the rep approve this discount? ``` The code tool should report *VP Sales approval required* (healthcare cap is 20%). The agent should cite the healthcare vertical rules and escalation matrix from `search_deal_policy`. 3. Try a deal the rep can approve: ```text A standard SaaS prospect wants 12% off a $40,000 annual contract on a 1-year deal. Can the rep approve this? ``` The code tool should report *rep can approve* (12% is within the 15% rep limit). **Result**: Congratulations!You have created an agent that can answer discount approval questions with a mix of policy citations and deterministic business rules. The agent uses two tools: `search_deal_policy` for citations and `check_discount_approval` for the definitive call. *** ## What's Next - Add more vertical rules or regional pricing tiers to the code tool init parameters. - Connect the agent to your CRM through an MCP server tool. For details, see [Use Your Pipeline as an MCP Tool](/docs/how-to-guides/productionizing-your-pipeline/expose-pipeline-as-mcp-tool.mdx). - Use [Prompt Explorer](/docs/how-to-guides/designing-your-pipeline/work-with-llms/using-prompt-studio.mdx) to refine the system prompt. - For more on agents and tools, see [Agent Tools](/docs/concepts/ai-agents/agent-tools.mdx). --- ## Tutorial: Building an IT Helpdesk Agent with Multiple Knowledge Bases Build an AI agent that answers employee IT questions by automatically deciding which knowledge base to search: an internal IT procedures database or a vendor software documentation database. The agent reads the question, picks the right tool, and synthesizes an answer from the relevant documents. The agent uses two search pipelines as tools. One pipeline searches the internal IT documentation, the other searches the vendor software documentation. The agent decides which tool to use based on the question. *** - **Level**: Intermediate - **Time to complete**: 25 minutes - **Prerequisites**: - A basic understanding of pipelines and indexes in . For details, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Indexes](/docs/concepts/indexes/indexes.mdx). - A basic understanding of agents in . For details, see [AI Agent](/docs/concepts/ai-agents/ai-agent.mdx). - A workspace in , where you'll create your agent and its tools. For help, see [Quick Start Guide](/docs/getting-started/quick-start-guide.mdx). - An API key from an active OpenAI account (or another model provider that supports tool calls). Connect to your OpenAI account. For help, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - **Goal**: After completing this tutorial, you'll have an IT helpdesk agent that answers employees questions based on two knowledge bases: an internal one and vendor documentation. This tutorial uses sample files for the knowledge bases. You can replace them with your own files. - **Keywords**: agent, tools, pipeline tool, knowledge base, RAG, routing *** ## What You're Building Employees ask two very different types of IT questions: - Internal process questions: "How do I request a software license?" or "What's the VPN access procedure?" These need answers from company-specific documentation and internal policies, IT procedures, and how-tos. - Software how-to questions: "How do I share my screen in Zoom?" or "How do I set up email on my phone?" These need answers from vendor product documentation. A single knowledge base struggles with both types of questions and combining them in one search often dilutes relevance. This tutorial shows you how to create two focused search pipelines, each backed by its own index, and wire them together into an agent that picks the right one for each question. ## Upload Files First, upload the sample files to your workspace: 1. Download the agent-it-helpdesk folder from gdrive and save it to a location on your computer. 2. Unzip the folder and open it. 3. In , go to *Files>Upload Files* and choose all the files in the folder. 4. Click **Upload**. **Result**: You have four files in your workspace: `vpn-access.md`, `software-requests.md`, `zoom-guide.md`, and `microsoft365-guide.md`. ## Add Metadata to the Files We'll add metadata to the files to mark internal knowledge base files and vendor documentation files. Based on the metadata, we'll create two separate indexes: one for internal IT documentation and one for vendor documentation. As we only have four files, we'll add metadata to the files manually. You can also use the SDK or REST API to add metadata to the files. For details, see [Add Metadata to Your Files](/docs/how-to-guides/working-with-your-data/working-with-metadata/add-metadata.mdx). 1. On the Files page, click More Actions next to the `zoom-guide.md` file and choose **View Metadata**. 2. Click **Add Metadata**. 3. Leave *Keyword* as type, type `knowledgebase` as the key, and `product` as the value, and save your changes. 4. Repeat steps 1 to 3 for the `microsoft365-guide.md` file. 5. For the `vpn-access.md` and `software-requests.md` files, leave *Keyword* as type, type `knowledgebase` as the key, and `internal` as the value, and save your changes. **Result**: You have added metadata to the files to differentiate between internal and vendor documentation. ## Create the Knowledge Bases We'll need two knowledge bases: one for internal documentation and one for vendor documentation. These knowledgebases will act as tools for the agent to help it answer user questions. Each knowledgebase needs an index and a search pipeline. ### Create the Index for Internal Documentation As we only have Markdown files, we'll create a simple index that uses the `MarkdownToDocument` component to convert the files to documents. Then, we'll use `MetadataRouter` to write only the documents with the `knowledgebase` metadata set to `internal` to the document store. :::tip Other File Types If you have other file types, you can start from the Standard Index (English) template and then add the `MetadataRouter` component to filter the documents based on the metadata. ::: 1. In the navigation, go to *Indexes>Create Index*. 2. Choose **Build your own**. 3. Type `internal-docs` as the index name. 4. Click **Create Index**. You're taken to the Builder. 5. In Builder, switch to the YAML view and paste the following index configuration: ```yaml # haystack-pipeline components: MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: "" max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: nested_fields: MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: internal_documents: conditions: - field: meta.knowledgebase value: internal operator: == operator: AND output_type: list[haystack.dataclasses.Document] connections: - sender: MarkdownToDocument.documents receiver: MetadataRouter.documents - sender: MetadataRouter.internal_documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: query: [] filters: [] files: - MarkdownToDocument.sources messages: [] ``` 6. Save and enable the index. **Result**: You have created an index for internal documentation. It filters the files to index based on their metadata. The query pipeline will use this index to search internal documents. ### Create the Index for Vendor Documentation This index only indexes files with the metadata `knowledgebase` set to `product`. 1. Go to *Indexes>Create Index* again. 2. Choose **Build your own**. 3. Type `vendor-docs` as the index name. 4. Click **Create Index**. You're taken to the Builder. 5. In Builder, switch to the YAML view and paste the following index configuration: ```yaml # haystack-pipeline components: MarkdownToDocument: type: haystack.components.converters.markdown.MarkdownToDocument init_parameters: table_to_single_line: false progress_bar: true store_full_path: false DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: "" max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: index.knn: true create_index: true http_auth: use_ssl: verify_certs: timeout: nested_fields: MetadataRouter: type: haystack.components.routers.metadata_router.MetadataRouter init_parameters: rules: product_documents: conditions: - field: meta.knowledgebase value: product operator: == operator: AND output_type: list[haystack.dataclasses.Document] connections: - sender: MarkdownToDocument.documents receiver: MetadataRouter.documents - sender: MetadataRouter.product_documents receiver: DocumentWriter.documents max_runs_per_component: 100 metadata: {} inputs: query: [] filters: [] files: - MarkdownToDocument.sources messages: [] ``` 6. Save and enable the index. **Result**: You have created an index for vendor documentation. It filters the files to index based on their metadata. The query pipeline will use this index to search vendor documents. ### Create the Internal Search Pipeline Let's create a RAG chat pipeline that the agent will use to query internal documentation. 1. In the navigation, go to *Pipeline Templates*. 2. Open the *Conversational* category, find the **RAG Chat** template, hover over it, and click **Use Template**. 3. Type `internal-it-search` as the pipeline name and click **Create Pipeline**. You're taken to Builder. 4. On the canvas, find the `OpenSearchDocumentStore` component and click it. This opens the configuration panel. 5. Choose *internal-docs* as the index. 6. Test the pipeline: Click **Run Pipeline** next to the `Input` component and type "How do I request VPN access?". The pipeline should return the answer from the internal documentation. 7. Save and deploy the pipeline. **Result**: You have created a RAG chat pipeline that searches the internal documentation. It's ready for the agent to use. ### Create the Vendor Docs Search Pipeline 1. Leave the Builder and click **Pipelines**. 2. Click More Actions next to the **internal-it-search** pipeline and choose **Duplicate**. The duplicated pipeline opens in Builder. 3. Change the pipeline name to `vendor-docs-search`. 4. Find the `OpenSearchDocumentStore` component and open its configuration. 5. Choose `product-docs` as the index. 6. Test the pipeline: Click **Run Pipeline** next to the `Input` component and type "How do I share my screen in Zoom?". The pipeline should return the answer from the vendor documentation. 7. Save and deploy the pipeline. **Result**: You have two search pipelines, each pointed at a different index. Now, let's create and agent that will use them as tools. ## Build the Agent Now you'll create the agent that uses both search pipelines as tools and routes questions between them. ### Create the Agent Pipeline 1. Go to *Pipelines>Create Pipeline>Create empty pipeline*. 2. Type `helpdesk-agent` as the pipeline name and click **Create Pipeline**. 3. Click **Add** to open the component library and drag the `Input`, `Agent`, and `Output` components onto the canvas. 4. Connect `Input` to `Agent`. 5. Connect `Agent` to `Output`. 6. Configure the Agent: 1. Click **Model** on the `Agent` component card to open its configuration panel. 2. Choose `gpt-5.4` (or another model that supports tool calls) from the list. 3. In the **System Prompt** field, paste the following prompt: ``` You are an IT helpdesk assistant for Acme Corp. You help employees solve IT problems and answer questions about IT processes and software. You have two tools: - search_internal_it: Use this for questions about Acme Corp's internal IT policies and procedures—requesting software, getting VPN access, IT support processes, internal how-tos. - search_vendor_docs: Use this for questions about how to use software products—Zoom, Microsoft 365, and other applications. When a question involves both internal processes and software (for example, "I can't connect to Teams because my VPN is blocking it"), use both tools before answering. Base your answer only on the information you find. Cite which documents you used. If you can't find the answer in either knowledge base, say so clearly and tell the employee to contact the IT helpdesk directly at helpdesk@acmecorp.internal. ``` 4. Leave the **User Prompt** field empty. You connected `Input.messages` to `Agent.messages`, so user questions from the chat window reach the agent directly. 5. In the Tools section, click **Add Tool**. 6. Choose **Pipeline** as the tool type. 7. On the Create Pipeline Tool window, choose to start from **Existing pipeline** and choose `internal-it-search` from the list. 8. Leave *Current draft* as the pipeline version. 9. Type `search_internal_it` as the tool name. 10. Type the following as the tool description: ``` Search Acme Corp's internal IT documentation. Use this tool for questions about internal IT policies, procedures, and processes—such as requesting software licenses, getting VPN access, IT support escalation, new employee IT setup, or any company-specific IT how-tos. ``` 11. Click **Add Pipeline Tool**. `search_internal_it` is added to the Tools section. 12. Click **Add Tool** again to add the second tool. 13. Choose **Pipeline** as the tool type. 14. On the Create Pipeline Tool window, choose to start from **Existing pipeline** and choose `vendor-docs-search` from the list. 15. Leave *Current draft* as the pipeline version. 16. Type `search_vendor_docs` as the tool name. 17. Type the following as the tool description: ``` Search vendor software documentation. Use this tool for questions about how to use specific applications and products—such as Zoom features, Microsoft 365, setting up email on mobile, or any other software how-to questions. ``` 18. Click **Add Pipeline Tool**. `search_vendor_docs` is added to the Tools section. 19. Close the Agent configuration panel. **Result**: You have created an agent pipeline with two tools: `search_internal_it` and `search_vendor_docs`. ## Test the Agent Before deploying, test the agent in Builder to confirm it routes questions correctly. 1. Click **Run** on the `Agent` component card. 2. In `messages`, type "How do I request access to vpn?" and run the agent. **Result**: The agent should call `search_internal_it`, find the VPN request procedure from `vpn-access.md`, and return step-by-step instructions including the IT Service Portal link. To check which tool was used, find a message with `"_role": "assistant"` in the component output and look for the `"tool_name"`. You can also test the agent with a question that requires both tools, such as: "I need to install Zoom on my laptop—how do I get a license and then set up the background?". The agent should call `search_internal_it` to find the software license request process, then call `search_vendor_docs` to find the virtual background instructions, and combine both into a single answer. ## Deploy the Agent 1. In Builder, click **Deploy**. 2. Wait until the pipeline status changes to *Deployed*. **Result**: Congratulations! Your helpdesk agent is live. You can now share it with your team and start using it to answer IT questions. For instructions on how to share the agent, see [Share a Pipeline Prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). ## What To Do Next Your agent is at the development service level. Before moving to production: - Test it with a wider range of employee questions to check that routing is accurate. - Adjust the tool descriptions and system prompt if the agent consistently picks the wrong tool for certain question types. --- ## Tutorial: Creating a Custom RegexBooster Component # Tutorial: Creating a Custom RegexBooster Component with a GitHub Template Write your own component, upload it to , and use it in your pipelines. In this tutorial, you'll create a `RegexBooster` component that adjusts document scores based on regex patterns. You'll then learn how to add it to your pipelines. *** - **Level**: Intermediate - **Time to complete**: 20 minutes - **Prerequisites**: - Good knowledge of Python. - Basic knowledge of regular expressions. - Understanding of how components and pipelines work. Read the following resources: - [Custom Components](/docs/concepts/about-pipelines/custom-components.mdx) - [Haystack Components](https://docs.haystack.deepset.ai/docs/components) - [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) - A GitHub account and basic knowledge of working with GitHub repositories. - API key with *Admin* role (Organization level). For instructions, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx) - **Goal**: After completing this tutorial, you'll have created a custom component that boosts document scores based on regex patterns. You'll then have uploaded this component to your workspace and added it to a pipeline. *** ## Prepare the Custom Components Template You'll create the component using a template we provide. First, we need to prepare it. 1. Fork the [dc-custom-component-template](https://github.com/deepset-ai/dc-custom-component-template) GitHub repository. 2. Clone the forked repository to your local machine. 3. Navigate to the `./dc-custom-component-template/src/dc_custom_component/example_components/` directory. 4. Delete the `preprocessors` folder. 5. Rename the `example_components`folder to `custom_components` and open it. The forked repo should now have the following structure: `./dc-custom-component-template/src/dc_custom_component/custom_components/rankers/`. 6. Open the `rankers` folder and rename the `keyword_booster.py` file to `regex_booster.py`. **Result**: Your template now has the following structure: ```text dc-custom-component-template/ ├── src/ │ └── dc_custom_component/ │ ├── __about__.py │ ├── __init__.py │ └── custom_components/ │ └── rankers/ │ └── regex_booster.py ├── pyproject.toml ├── README.md └── tests/ ``` ## Set Up a Virtual Environment 1. Install Hatch by running: `pip install hatch`. 2. In your terminal, navigate to the root directory (`./dc-custom-component-template`) of your cloned repository. 3. Create a virtual environment by running: `hatch shell`. **Result**: The virtual environment is running. ## Implement RegexBooster 1. Open the `./dc-custom-component-template/src/dc_custom_component/custom_components/rankers/regex_booster.py` file. 2. Paste the following code replacing all the file contents, and save the file. ```python from typing import Dict, List from haystack import component, Document @component class RegexBooster: r""" A component for boosting document scores based on regex patterns. This component adjusts the scores of documents based on whether their content matches specified regular expression patterns. After adjusting scores, it sorts the documents in descending order of their new scores. Note: - Regex matching is case-insensitive by default. - Multiple regex patterns can match a single document, in which case the boosts are multiplied together. - Documents that don't match any patterns keep their original score. - The component assumes documents already have a 'score' attribute. Documents without a score are treated as having a score of 0. Example: \```python booster = RegexBooster({ r"\bpython\b": 1.5, # Boost documents mentioning "python" by 50% r"machine\s+learning": 1.3, # Boost "machine learning" by 30% r"\bsql\b": 0.8, # Reduce score for documents mentioning "sql" by 20% }) \``` In this example, a document containing both "python" and "machine learning" would have its score multiplied by 1.5 * 1.3 = 1.95, effectively boosting it by 95%. """ def __init__(self, regex_boosts: Dict[str, float]): self.regex_boosts = {re.compile(k, re.IGNORECASE): v for k, v in regex_boosts.items()} """ Initialize the component. :param regex_boosts: A dictionary where: - Keys are string representations of regular expression patterns. - Values are float numbers representing the boost factor. The boost factor must be greater than 1.0 to increase the score, or between 0 and 1 to decrease it. A boost of exactly 1.0 will have no effect. """ @component.output_types(documents=List[Document]) def run(self, documents: List[Document]) -> Dict[str, List[Document]]: """ Apply regex-based score boosting to the input documents. :param documents: The list of documents to process. Returns: A dictionary with a single key 'documents', containing the list of processed documents, sorted by their new scores. """ for regex, boost in self.regex_boosts.items(): for doc in documents: if doc.score is not None and regex.search(doc.content): doc.score *= boost documents = sorted(documents, key=lambda x: x.score or 0, reverse=True) return {"documents": documents} ``` 3. Format your code by running `hatch run code-quality:all` from the project root directory. 4. To help you track changes to the component, update its version: 1. Open the `./dc-custom-component-template/src/dc_custom_component/__about__.py` file. 2. Update the version number to the next one. For example, if the current version is 1.0.0, update it to 1.0.1. **Result**: The Python implementation for the `RegexBooster` component is now in the `regex_booster.py` file, the code is formatted, and the component version is updated. ## Add Tests 1. Open the `./dc-custom-component-template/tests` folder and delete the `example_components` folder. 2. Create a file called `test_regex_booster.py`. 3. Paste this code into this file and save it: ```python from typing import List, Dict, Any from haystack import component, Document, Pipeline from haystack.components.joiners import DocumentJoiner from dc_custom_component.custom_components.rankers.regex_booster import RegexBooster # Unit Tests def test_regex_booster_initialization() -> None: booster = RegexBooster({"pattern": 1.5}) assert len(booster.regex_boosts) == 1 assert list(booster.regex_boosts.values())[0] == 1.5 def test_regex_booster_case_insensitivity() -> None: booster = RegexBooster({r"\bPython\b": 1.5}) doc = Document(content="python is great", score=1.0) result = booster.run(documents=[doc]) assert result["documents"][0].score == 1.5 def test_regex_booster_multiple_patterns() -> None: booster = RegexBooster({r"\bPython\b": 1.5, r"\bgreat\b": 1.2}) doc = Document(content="Python is great", score=1.0) result = booster.run(documents=[doc]) assert result["documents"][0].score == 1.5 * 1.2 def test_regex_booster_no_match() -> None: booster = RegexBooster({r"\bJava\b": 1.5}) doc = Document(content="Python is great", score=1.0) result = booster.run(documents=[doc]) assert result["documents"][0].score == 1.0 def test_regex_booster_sorting() -> None: booster = RegexBooster({r"\bPython\b": 1.5, r"\bJava\b": 1.2}) docs = [ Document(content="Java is okay", score=1.0), Document(content="Python is great", score=1.0), Document(content="C++ is fast", score=1.0), ] result = booster.run(documents=docs) assert [doc.content for doc in result["documents"]] == [ "Python is great", "Java is okay", "C++ is fast", ] def test_regex_booster_no_score() -> None: booster = RegexBooster({r"\bPython\b": 1.5}) doc = Document(content="Python is great") result = booster.run(documents=[doc]) assert result["documents"][0].score is None # Integration Tests @component class MockRetriever: @component.output_types(documents=List[Document]) def run(self, query: str) -> Dict[str, Any]: docs = [ Document(content="Python is a programming language", score=0.9), Document(content="Java is also a programming language", score=0.7), Document(content="Machine learning is a subset of AI", score=0.5), ] return {"documents": docs} @pytest.fixture def regex_pipeline() -> Pipeline: retriever = MockRetriever() regex_booster = RegexBooster({r"\bPython\b": 1.5, r"\bAI\b": 1.3}) joiner = DocumentJoiner() pipeline = Pipeline() pipeline.add_component("retriever", retriever) pipeline.add_component("regex_booster", regex_booster) pipeline.add_component("joiner", joiner) pipeline.connect("retriever.documents", "regex_booster.documents") pipeline.connect("regex_booster.documents", "joiner.documents") return pipeline def test_regex_booster_in_pipeline(regex_pipeline: Pipeline) -> None: results = regex_pipeline.run(data={"query": "programming languages"}) documents = results["joiner"]["documents"] assert len(documents) == 3 assert documents[0].content == "Python is a programming language" assert pytest.approx(documents[0].score, 0.01) == 0.9 * 1.5 assert documents[1].content == "Java is also a programming language" assert pytest.approx(documents[1].score, 0.01) == 0.7 assert documents[2].content == "Machine learning is a subset of AI" assert pytest.approx(documents[2].score, 0.01) == 0.5 * 1.3 def test_regex_booster_pipeline_no_matches() -> None: @component class NoMatchRetriever: @component.output_types(documents=List[Document]) def run(self, query: str) -> Dict[str, Any]: return { "documents": [ Document(content="C++ is a compiled language", score=0.8), Document(content="Ruby is dynamic", score=0.6), ] } new_pipeline = Pipeline() new_pipeline.add_component("retriever", NoMatchRetriever()) new_pipeline.add_component( "regex_booster", RegexBooster({r"\bPython\b": 1.5, r"\bAI\b": 1.3}) ) new_pipeline.add_component("joiner", DocumentJoiner()) new_pipeline.connect("retriever.documents", "regex_booster.documents") new_pipeline.connect("regex_booster.documents", "joiner.documents") results = new_pipeline.run(data={"query": "programming languages"}) documents = results["joiner"]["documents"] assert len(documents) == 2 assert documents[0].content == "C++ is a compiled language" assert pytest.approx(documents[0].score, 0.01) == 0.8 assert documents[1].content == "Ruby is dynamic" assert pytest.approx(documents[1].score, 0.01) == 0.6 ``` 4. From the root directory of your project, where the `pyproject.toml` is located, run: ```shell hatch run tests ``` If the tests pass, you can upload your component to . 5. Push your changes to the forked repository. ## Import RegexBooster to We use GitHub Actions to build and push components to . Create a new release for your forked repository and assign a tag to it to trigger the build and the push jobs: 1. Add the `DEEPSET_CLOUD_API_KEY` secret to your repository. This is your API key that you prepared in the prerequisites. 1. In your forked repository, go to _Settings > Secrets and variables > Actions_. 2. Click **New repository secret**. 3. Type `DEEPSET_CLOUD_API_KEY` as the secret name and paste the API key in the _Secret_ field. 4. Click **Add secret**. For details on GitHub secrets, see [Using secrets in GitHub actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions). 2. Make sure your repository has workflows enabled. Go to _Actions_ and click **Enable workflows**. 3. Create a new release: 1. In your forked repository, go to *Code* and on the right-hand side, find _Releases_. Click **Create a new release**. 2. Click **Choose a tag** and type `1.0.0` as the tag name. 3. Click **Create a new tag**. 4. Click **Publish release**. This triggers tests and code quality check. If these pass, your component is imported to . You can check the status in the _Actions_ tab of your forked repository. _Note_: It can take up to 5 minutes to be available in the Platform. **Result**: RegexBooster is in , ready to be added to a pipeline. ## Add RegexBooster to a Pipeline Let's quickly create a pipeline. If you have one ready, open it in Builder. 1. Go to **Pipeline Templates**. 2. Choose **Document Search** templates, hover over _Semantic Document Search_, and click **Use template**. 3. Click **Create a pipeline**. You're redirected to Pipeline Builder. 4. Find the `Ranker` in your query pipeline components, click More Actions on the component card and choose _Delete_. 5. Click **Add** to open the component library, find `RegexBooster` and drag it onto the canvas. 6. On the `RegexBooster` card, click **Configure** under the `regex_boosts` parameter and enter the following configuration: ```yaml '\bcovid-19\b|\bcoronavirus\b': 2.0 '\bcancer\b': 1.5 '\basthma\b': 1.3 '\btreatment\b': 1.2 '\bsymptoms\b': 1.1 ``` 8. Draw a connection from `embedding_retriever`'s documents output to `RegexBooster`'s documents input. 9. Draw another connection from `RegexBooster`'s documents output to `Output`'s documents. This is what your canvas should look like: :::tip Connections You can manage component connections using the Connections panel at the bottom of the canvas. ::: 10. If you don't have autosave enabled, save your pipeline. 11. Find `OpenSearchDocumentStore` among your pipeline components and click it to open the configuration. You'll notice it shows a warning that an index is missing. If you have an enabled index ready, select it, and go to the last step of this instruction. Otherwise, continue with the next step. 12. Click the `index` field and then click **Create Index**. 13. Choose the *Standard Index (English)* template, leave the default name, and click **Create Index**. 14. When you're redirected to Builder, click **Enable** in the top right corner. This indexes the files and makes them ready for search. 15. Leave Builder, go to **Pipelines** and open the *Semantic Document Search* pipeline. 16. Click the `OpenSearchDocumentStore` component card and choose the *Standard-Index-English* index you just created. 17. Save your changes and deploy the pipeline. Here's the complete YAML configuration of your pipeline: ```yaml #haystack-pipeline components: query_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.text_embedder.DeepsetNvidiaTextEmbedder init_parameters: normalize_embeddings: true model: intfloat/e5-base-v2 embedding_retriever: # Selects the most similar documents from the document store type: haystack_integrations.components.retrievers.opensearch.embedding_retriever.OpenSearchEmbeddingRetriever init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: Standard-Index-English max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: top_k: 20 # The number of results to return RegexBooster: type: dc_custom_component.custom_components.rankers.regex_booster.RegexBooster init_parameters: regex_boosts: \bcovid-19\b|\bcoronavirus\b: 2 \bcancer\b: 1.5 \basthma\b: 1.3 \btreatment\b: 1.2 \bsymptoms\b: 1.1 connections: # Defines how the components are connected - sender: query_embedder.embedding receiver: embedding_retriever.query_embedding - sender: embedding_retriever.documents receiver: RegexBooster.documents inputs: # Define the inputs for your pipeline query: # These components will receive the query as input - "query_embedder.text" filters: # These components will receive a potential query filter as input - "embedding_retriever.filters" outputs: # Defines the output of your pipeline documents: "RegexBooster.documents" # The output of the pipeline is the retrieved documents max_runs_per_component: 100 metadata: {} ``` ## Test the Pipeline with RegexBooster Let's see if it works on real files. 1. Download this [set of medical articles](https://drive.google.com/file/d/1iMhMpJWTtk3WiUfSzHpYUKWH6IPmJpGF/view?usp=drive_link) and extract it to your machine. You should have a set of 10 articles. 2. In , open the same workspace where you created the _Semantic_Document_Search_ pipeline and go to **Files**. 3. Click **Upload files**, choose the files you extracted in step 1, and click **Upload**. 4. Let's create a document search pipeline without `RegexBooster` to compare the results: 1. Go to **Pipeline Templates**. 2. Choose **Document Search** templates, hover over _Semantic Document Search_, and click **Use template**. 3. Change the pipeline name to `no_regex` and click **Create Pipeline**. 4. Once you're redirected to Builder, find `OpenSearchDocumentStore` and choose `Standard-Index-English` as the index. If you used another index when creating the `RegexBooster` pipeline, choose the same index. 5. Save and deploy the pipeline. 5. When the pipeline is deployed, go to **Playground** and choose the _Semantic_Document_Search_ pipeline. 6. In the _Search_ field, type the following query: `Tell me about ongoing medical research`. You can see that the top three documents are about coronavirus, cancer, and asthma. All of them are keywords `RegexBooster` prioritizes. 7. Now, let's change the pipeline to the `no_regex` one and repeat the same query. The top three documents are about Alzheimer, coronavirus, and cancer. The ranking of documents is different if we're not prioritizing certain keywords. **Congratulations!**: You have implemented your custom component and imported it to . You can now run pipelines with `RegexBooster`! --- ## Tutorial: Demoing Your App Share your pipeline with others and let them try it out. It may seem an easy topic, but there are a couple of things to consider here, for example, user expectations, to make your demo successful. *** - **Level**: Intermediate - **Time to complete**: 10 minutes - **Prerequisites**: - This tutorial assumes some basic knowledge of . It also assumes that you have a created and deployed pipeline ready. If you don't, you can complete the [Tutorial: Building a Robust RAG App](/docs/tutorials/learn-the-basics/tutorial-building-a-robust-rag-system.mdx), [Tutorial: Building Your First Document Retrieval App](/docs/tutorials/learn-the-basics/tutorial-building-your-first-document-search-app.mdx), or [Tutorial: Building a Robust RAG System](/docs/tutorials/learn-the-basics/tutorial-building-a-robust-rag-system.mdx) - You must be an Admin to complete this tutorial. - **Goal**: After completing this tutorial, you will have demonstrated your pipeline to other users and collected their feedback. *** ## Prepare for Inviting Users It's important to always get feedback from real users as it gives you an idea of your pipeline performance. Before other users can test your pipeline, you must make them aware of a couple of things: - Ensure your users understand that if they ask for information about documents that don't exist in , the system won't be able to find an answer. - Ensure the users understand that the information they're looking for must exist in the text data stored in . The application cannot make up answers by itself. - Explain what queries work well (for example, natural language questions instead of simple keywords or copy-pasted error messages). - Make your users aware of the data indexed in their search application. **Result**: The users know how to use your pipeline and what to expect. They're ready to run a search with your pipeline and provide feedback. ## Share Your Pipeline Prototype Users don't need a account to try your pipeline. You generate a link to the prototype of your pipeline. This link gives them access to the search page to run searches with your pipeline prototype. You can style the prototype with your brand logo and colors. 1. Log in to . 2. Click **Pipelines**. 3. Find a deployed pipeline you want to share, and click **Share** next to it. The Share as Prototype window opens. 4. On the **Settings** tab: 1. Select the link expiration date. When the link expires, people can no longer access the pipeline prototype. 2. Add the pipeline description. This can be guidelines, things you want users to pay attention to, and so on. The description will be visible to the users on the Search page. 3. Choose if you want to enable login for this prototype. If you do that, only logged in users who belong to your organization will be able to view the prototype. Otherwise, anyone with the link will be able to access it. 4. If needed, enable the metadata filters. When you enable this option, the metadata from your files are used as search filters. 5. Choose if you want users to be able to view the source documents. 5. Open the **Style** tab to add your company logo and colors to the prototype. 6. Generate and copy the link. 7. Close the window. 8. Share the link with the people you think should test your pipeline. **Result**: You have shared your pipeline prototype with real users. They can now run a search and give feedback in . ## Ask Your Users to Run a Search and Give Feedback Explain to your users the steps to run a search: 1. Open the link they got from you. They land on the Search page without access to other pages in . 2. Ask a question and click **Search**. 3. Click a thumbs icon below the answer to indicate if it's correct. You can add additional feedback to explain your choice in the text field that opens. You can also copy the answer or save it for later. :::info Save for later If you have a account, you can find answers you've saved for later in the pipeline's query history. To view them, click the pipeline name, go to *Analytics* and open *History*. In the table, use the filter to show only bookmarked records. ::: **Result**: You have explained to your users how to run a search and evaluate the answers. They can now start giving you feedback. ## Analyze User Feedback The feedback is displayed on the Analytics page. You can also export it to a CSV file. 1. In , go to **Pipelines** and click the name of the pipeline you shared. 2. Switch to *Analytics*. The Overview tab shows the overall feedback and queries. 2. Go to **History** and customize the table to show feedback rating: 1. Click **Manage table preferences**. 2. Choose Feedback Rating and Feedback Notes columns and close the window. You can now see queries with their feedback rating and notes. You can also export the Search History table to a CSV file. ::: AI-Powered Insights You can use the AI-powered Feedback Insights panel to analyze feedback patterns and generate executive summaries to help you understand performance trends and identify areas for improvement. ::: **Result**: Congratulations! You have demonstrated your pipeline to real users and collected their feedback. You can now use it to tweak your pipeline and achieve the best performance. --- ## Tutorial: Uploading Files with Python Methods Use a Python SDK to quickly upload large amounts of files. This method supports uploading metadata. It uses an open source SDK package. *** - **Level**: Intermediate - **Time to complete**: 10 minutes - **Prerequisites**: - You must be an Admin to complete this tutorial. - You need a basic knowledge of Python. - The workspace where you want to upload the files must already be created in . In this tutorial, it's called `hotel_reviews`. - **Goal**: After completing this tutorial, you will have uploaded a set of hotel reviews with metadata to a workspace using a Python script. You can replace this dataset with your custom one. *** ## Prepare Your Files This tutorial uses a set of hotel reviews with some metadata in them. You can also use your own files; just make sure they have lowercase extensions, for example _myfile.txt_ instead of _myfile.TXT_. 1. Download [the hotel reviews dataset](https://drive.google.com/file/d/1T4ngb51UYIUIU1HVvEe4DzDzt4By0xSl/view?usp=sharing). 2. Extract the files to a folder called _hotel_reviews_ in your _Documents_ folder. This can take a couple of minutes. **Result**: You have 5,956 files in the `_\Documents\hotel_reviews_` folder, 2978 TXT files and 2978 JSON files. Each TXT file is accompanied by a `.meta.json` file containing the text file metadata. ## Install the SDK 1. Open the command line and run: ```powershell pip install deepset-cloud-sdk ``` 2. Wait until the installation finishes with a success message. **Result**: You have installed the SDK. It comes with a command line interface that we'll use to upload the files. ## Obtain the API Key 1. Log in to [](https://cloud.deepset.ai/). 2. Click your profile icon and choose _Connections_. 3. Under *API Keys*, click **Add new key**. 4. Choose the expiration date for your key and click **Generate key**. 5. Copy the key and save it to a notepad. 6. Click **Done**. **Result**: You have an API key saved in a file. You can now use it to upload your files. ## Upload Files 1. Write a script that will upload the files from a specified path: 1. In the same folder where you saved the _hotel_reviews_ files, create a Python script called `hotel_reviews_upload.py`. 2. Copy the code from the example below: ```python from pathlib import Path from deepset_cloud_sdk.workflows.sync_client.files import upload ## Uploads all files from a given path. upload( paths=[Path("")], # provide a path to the folder on your computer where you saved the hotel_reviews folder api_key="", # the API key to connect to deepset workspace_name="", # the workspace where you want to upload files blocking=True, # waits until the files are displayed in deepset, # this may take a couple of minutes timeout_s=300, # the timeout for the `blocking` parameter in number of seconds show_progress=True, # shows the progress bar recursive=True, # uploads files from all subfolders as well ) ``` 2. Save the script and run it: ```python python hotel_reviews_upload.py ``` 3. Wait until the upload finishes successfully. You should see this message: 5956 files are uploaded, and half of them, 2978, are listed in . (The metadata files are not shown in ). **Result**: You have uploaded all your files, including the ones from the subfolders. Let's now see if they're showing up in . ## Verify the Upload - In the command line, list the uploaded files by running: ```python deepset-cloud list-files ``` ```python python -m deepset_cloud_sdk.cli list-files ``` You should see a list of files with file ID, URL, name, size, metadata, and the date when it was created. The number of files we uploaded makes it easier to verify if they uploaded correctly in the UI. - In : 1. Switch to the _hotel_reviews_ workspace where you uploaded the files and check the workspace statistics. You should see "3K" above files. 2. In the navigation, click **Files** and check if the files are showing on the Files page. - Now, let's check if the metadata was uploaded: 1. In the navigation, click **Files**. 2. Click any file that has metadata and choose _View Metadata_. You should see the file's metadata. --- ## Tutorial: Automatically Tagging Your Data with an LLM Create an index that uses a large language model to tag your data and add the tags to metadata. Labelling data with an LLM provides a fast, consistent, and scalable way of adding metadata to your files. *** - **Level**: Beginner - **Time to complete**: 20 minutes - **Prerequisites**: - A basic understanding of how indexes work. To learn more, see [Indexes](/docs/concepts/indexes/indexes.mdx). - A workspace where you'll upload the data and create the index. For instructions on how to create a workspace, see [Quick Start Guide](/docs/getting-started/quick-start-guide.mdx). - An API key for the workspace. For information how to generate it, see [Generate API Keys](/docs/how-to-guides/managing-access/generate-api-key.mdx). - **Goal**: After completing this tutorial, you'll have created an index that uses an LLM to tag your data. The tags the LLM generates will be stored in each file's metadata so you can use them in your search app. You'll use an example dataset of emails to do this. *** ## Upload Data First, let's upload the data to the workspace where we'll then create the auto-labelling index. 1. Download the [sample emails dataset](https://drive.google.com/file/d/1OhMXttGLGR862j67eagev1cPmI-vpREz/view?usp=drive_link) and unpack it on your computer. This is a collection of emails you'll tag. you can also use your own files. 2. Log in to , make sure you're in the right workspace, and go to *Files*. 3. Click **Upload Files**, drag the files you unpacked in step 1 and drop them in the Upload Files window. (You must select all files in the folder, doesn't support uploading folders.) 4. Click **Upload** and wait until the files are in the workspace. **Result**: Your files are in the workspace and you can see them on the Files page. ## Create an Index Once your data is in , you can create an index that will be the starting point for the auto-labelling system. The index prepares files for search and writes them into a document store, where a query pipeline can access them. 1. Go to *Indexes* and click **Create Index**. This opens available index templates. 2. Click the **AI-Generated Metadata for Files** index to use it. 3. Leave the default index name and click **Create Index**. You land in Builder with the index open for editing.. **Result**: You created an index that can preprocess multiple file types and extract title and summary from the files. ## Adjust the Index This index uses an LLM to extract the file title and generate a file summary that it then adds to each file's metadata. It's also designed to preprocess multiple file types, while we only need to preprocess text files. Let's simplify preprocessing and update the prompt to tag the emails with: * Urgency * Type * Action required ### Simplify preprocessing *Note*: This step is optional, but it gets rid of components you don't need and makes the index simpler. You can also leave the index as is, it will work correctly too, using only the converters it needs to preprocess the files. The emails from the dataset are text files, so you only need a text file converter. Let's remove all the other converters. 1. Zoom in using the zoom-in icon (+) at the bottom of the page. 2. Scroll up, find `csv_converter`, and click More Actions on the component. You'll see all available actions for this component. 3. Click **Delete** . 4. Repeat steps 2 and 3 for the following components: - `pdf_converter` - `markdown_converter` - `html_converter` - `docx_converter` - `pptx_converter` - `xlsx_converter` You should only have the `text_converter` left, connected to `file_classifier` and `LLMMetadataExtractor`: 5. With only one file type to process, you don't need `file_classifier`. Delete the component and connect `text_converter`'s `sources` to `Input`. **Result**: You have adjusted the index to your needs, getting rid of unnecessary components and configurations. `text_converter` now receives files directly from `FilesInput` and, converts them into documents and sends them to the LLM to annotate. The annotated documents are then preprocessed and written into the document store. This is what your index looks like now:
Index YAML ```yaml components: text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 normalize_embeddings: true meta_fields_to_embed: - context writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: search_fields: - content - context policy: OVERWRITE splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en LLMMetadataExtractor: type: haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor init_parameters: prompt: | Please extract the following metadata for the provided document: - "title": A short title describing the content - "summary": A 2 sentence summary of the content document: {{ document.content | truncate(25000) }} Answer exclusively with the JSON object as plain text. Use NO code blocks, NO markdown formatting, NO prefixes like "json" or similar. Begin your response directly with { and end with }. Required structure: { "title": "", "summary": "" } chat_generator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: "us.anthropic.claude-sonnet-4-20250514-v1:0" boto3_config: region_name: us-west-2 read_timeout: 120 retries: total_max_attempts: 3 mode: standard generation_kwargs: max_tokens: 650 expected_keys: - summary - title connections: # Defines how the components are connected - sender: document_embedder.documents receiver: writer.documents - sender: splitter.documents receiver: document_embedder.documents - sender: LLMMetadataExtractor.documents receiver: splitter.documents - sender: text_converter.documents receiver: LLMMetadataExtractor.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - text_converter.sources max_runs_per_component: 100 metadata: {} ```
### Update the Prompt Now, let's update the prompt to tag the emails with specific attributes. 1. Find the `LLMMetadataExtractor` and click it. This opens the configuration panel where you can update the prompt. 2. Delete the current prompt and replace it with the following text: ```text You are an email annotation assistant. For each email, analyze it and return a JSON object with the following fields: - "urgency": one of "high", "medium", or "low". - "type": one of "meeting request", "status update", "question", "announcement", or "other". - "action required": either "yes" or "no". Your answer must only be the JSON object, starting with { and ending with }, with no extra text, explanations, or formatting. --- Guidelines for annotation Urgency - "high": - Mentions a near-term deadline (e.g., today, tomorrow, this week). - Explicitly marked urgent or requires immediate attention. - Requests blocking input or decisions. - "medium": - Requests action but not immediate (within a few days). - Important updates with some implied timeliness. - "low": - Informational only, no clear deadline. - General announcements or FYI. Type - "meeting request": Asks to schedule, confirm, or prepare for a meeting. - "status update": Provides progress reports, updates on work, results. - "question": Primarily asks for information or clarification. - "announcement": Broadcasts general info, policy changes, or news. - "other": Anything that doesn’t fit the above categories. Action required - "yes": Recipient is asked to reply, decide, confirm, attend, or do something. - "no": Purely informational, no expectation of response or action. --- Tie-breaking rules 1. Meeting request > Question > Status update > Announcement > Other - Example: If an email both asks a question and proposes a meeting → classify as "meeting request". 2. If urgency is ambiguous, default to "medium". 3. If action required is unclear, default to "no". --- Example Input: "Hi team, could you please confirm your availability for tomorrow’s sync?" Example Output: { "urgency": "high", "type": "meeting request", "action required": "yes" } Email: {{ document.content }} ``` 3. Optionally, configure the expected metadata keys: 1. In the `LLMMetadataExtractor` configuration panel, click **Advanced**. 2. Under `Expected keys`, type: ```text - urgency - type - action ``` *Tip*: You can also leave `expected keys` blank. Filling it in submits a warning log if the keys in the `expected_keys` list don't appear in the LLM response. 4. Save your index. **Result**: You have updated the prompt to add the following metadata to the documents: * Urgency: high, medium, low * Type: meeting request, status update, question, announcement, other * Action required: yes, no Your index is ready to process your files.
Index YAML ```yaml components: text_converter: type: haystack.components.converters.txt.TextFileToDocument init_parameters: encoding: utf-8 store_full_path: false document_embedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/e5-base-v2 normalize_embeddings: true meta_fields_to_embed: - context writer: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: search_fields: - content - context policy: OVERWRITE splitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 250 split_overlap: 30 respect_sentence_boundary: true language: en LLMMetadataExtractor: type: haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor init_parameters: prompt: | You are an email annotation assistant. For each email, analyze it and return a JSON object with the following fields: - "urgency": one of "high", "medium", or "low". - "type": one of "meeting request", "status update", "question", "announcement", or "other". - "action required": either "yes" or "no". Your answer must only be the JSON object, starting with { and ending with }, with no extra text, explanations, or formatting. --- Guidelines for annotation Urgency - "high": - Mentions a near-term deadline (e.g., today, tomorrow, this week). - Explicitly marked urgent or requires immediate attention. - Requests blocking input or decisions. - "medium": - Requests action but not immediate (within a few days). - Important updates with some implied timeliness. - "low": - Informational only, no clear deadline. - General announcements or FYI. Type - "meeting request": Asks to schedule, confirm, or prepare for a meeting. - "status update": Provides progress reports, updates on work, results. - "question": Primarily asks for information or clarification. - "announcement": Broadcasts general info, policy changes, or news. - "other": Anything that doesn’t fit the above categories. Action required - "yes": Recipient is asked to reply, decide, confirm, attend, or do something. - "no": Purely informational, no expectation of response or action. --- Tie-breaking rules 1. Meeting request > Question > Status update > Announcement > Other - Example: If an email both asks a question and proposes a meeting → classify as "meeting request". 2. If urgency is ambiguous, default to "medium". 3. If action required is unclear, default to "no". Example Input: "Hi team, could you please confirm your availability for tomorrow’s sync?" Example Output: { "urgency": "high", "type": "meeting request", "action required": "yes" } Email: {{ document.content }} chat_generator: type: haystack_integrations.components.generators.amazon_bedrock.chat.chat_generator.AmazonBedrockChatGenerator init_parameters: model: "us.anthropic.claude-sonnet-4-20250514-v1:0" boto3_config: region_name: us-west-2 read_timeout: 120 retries: total_max_attempts: 3 mode: standard generation_kwargs: max_tokens: 650 expected_keys: - urgency - type - action page_range: '' connections: # Defines how the components are connected - sender: document_embedder.documents receiver: writer.documents - sender: splitter.documents receiver: document_embedder.documents - sender: LLMMetadataExtractor.documents receiver: splitter.documents - sender: text_converter.documents receiver: LLMMetadataExtractor.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - text_converter.sources max_runs_per_component: 100 metadata: {} ```
## Index Your Files Let's preprocess the files, add metadata, and write the resulting documents into the document store: 1. In Builder, click **Enable** to start indexing. The index status changes to _Indexing_. Hover your mouse over the _Indexing_ label to check progress: 2. Wait until the status changes to _Indexed_. ## Verify Metadata For most file types, you can preview the documents that were created from a file, together with their metadata, in . To do this, just click the file. You'll see the preview and the metadata.The emails you uploaded are of a type whose previews are not supported in . Use this Colab notebook to analyze the metadata stored in the document store: [Haystack Enterprise Platform Document Metadata Checker](https://colab.research.google.com/drive/1xsgwu3bGt6U4JKE7Sh23YJPQQ-8W8MKe?usp=sharing). **Result**: Congratulations! You have created an index that can add metadata to documents and store them in a document store. You've adjusted the index to get rid of unnecessary components and changed the prompt to instruct the LLM to label the documents in a specific way. # What's Next You can now use the labelled documents in your query pipeline. For example, you can use [MetadataRouter](/docs/reference/pipeline-components/logic-and-flow/MetadataRouter.mdx) or [ConditionalRouter](/docs/reference/pipeline-components/logic-and-flow/ConditionalRouter.mdx) to route the documents based on their metadata values to specific pipeline branches. --- ## Tutorial: Build a PII Masking Index # Tutorial: Build a PII Masking Index with Custom Code Build an index that hides sensitive personal information using custom code. This tutorial is a great starting point if you're building an app where you need to keep sensitive data out of the LLM, such as a CV screening system. You'll also learn how ot use the `Code` component in your apps. *** - **Level**: Beginner - **Time to complete**: 10 minutes - **Prerequisites**: - You must have an Editor role in the workspace where you'll create the index. - You must have a workspace where you'll create the index. For instructions on how to create a workspace, see [Quick Start Guide](/docs/getting-started/quick-start-guide.mdx). - **Goal**: After completing this tutorial, you'll have create an index that can process PDF and TXT files and masks sensitive personal information using custom code. You'll also learn how to use the `Code` component in your apps. *** ## Create the Index To keep it simple, let's create an index that can process PDF files. 1. In , make sure in the correct workspace and go to **Indexes**. 2. Click **Create Index>Build your own** to create an index from scratch. 3. Type *PII-masking-index* as the name and *An index that masks sensitive personal information* as the description and click **Create Index**. 4. Click **Components** to open the component library and drag the following components onto the canvas: :::tip You can use the search field in the Component Library to find components quickly. ::: - `Input` - `PDFMinerToDocument` - `Code` - `DocumentSplitter` - `DeepsetNvidiaDocumentEmbedder` - `DocumentWriter` - `OpenSearchDocumentStore` 5. Click the `Code` component to open the code editor. You can expand it to make it more convenient. 6. Replace the example code with the following code: ```python from haystack import component, Document from typing import List @component class Code: """ Masks personally identifiable information in CV text before LLM processing. """ @component.output_types(cleaned_docs=List[Document]) def run(self, documents: List[Document]) -> dict: cleaned_docs = [] for doc in documents: redacted = doc.content # Email addresses email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b' redacted = re.sub(email_pattern, '[EMAIL]', redacted) # LinkedIn URLs linkedin_pattern = r'linkedin\.com/in/[A-Za-z0-9_-]+' redacted = re.sub(linkedin_pattern, '[LINKEDIN]', redacted, flags=re.IGNORECASE) # GitHub URLs github_pattern = r'github\.com/[A-Za-z0-9_-]+' redacted = re.sub(github_pattern, '[GITHUB]', redacted, flags=re.IGNORECASE) # Phone numbers: +44 7700 112233, 07700 112233, 798072811, etc. phone_pattern = r'(\+\d{1,3}[\s.-]?)?\(?\d{2,4}\)?[\s.-]?\d{3,4}[\s.-]?\d{3,4}|\b\d{9,11}\b' redacted = re.sub(phone_pattern, '[PHONE]', redacted) # UK postcodes: BS8 1AF, M1 4HE, EC1A 1BB postcode_pattern = r'\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b' redacted = re.sub(postcode_pattern, '[POSTCODE]', redacted, flags=re.IGNORECASE) # Street addresses (line containing number + street type) street_pattern = r'\d+\s+[\w\s]+(?:Street|St|Road|Rd|Avenue|Ave|Lane|Ln|Drive|Dr|Way|Court|Ct|Place|Pl|Square|Sq|Close|Crescent|Terrace|Grove|Park|Gardens|Row|Mews|Hill|Green|Wood|Gate|Walk|Fields|Rise|View|Valley|Meadow|Heights)\b[^,\n]*' redacted = re.sub(street_pattern, '[ADDRESS]', redacted, flags=re.IGNORECASE) # Date of birth patterns: DOB: 15/03/1988, Date of Birth: 15 March 1988 dob_pattern = r'(DOB|Date of Birth|Born|Birthday|D\.O\.B\.?)[\s:]*\d{1,2}[\s./-](\d{1,2}|Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[\s./-]\d{2,4}' redacted = re.sub(dob_pattern, '[DATE_OF_BIRTH]', redacted, flags=re.IGNORECASE) # National Insurance Number (UK): AB 12 34 56 C nino_pattern = r'\b[A-Z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-Z]\b' redacted = re.sub(nino_pattern, '[NATIONAL_ID]', redacted, flags=re.IGNORECASE) cleaned_docs.append(Document(content=redacted, meta=doc.meta)) return {"cleaned_docs": cleaned_docs} ``` Your code is instantly validated. 7. Close the code editor. 8. Connect the components as follows: **Tip**: Just drag lines between components to connect them. Builder will automatically create the connections for you, joining compatible outputs with compatible inputs. - Connect `Input`'s `file` output to `PDFMinerToDocument`'s `sources` input. - Connect `PDFMinerToDocument`'s `documents` output to `Code`'s `documents` input. - Connect `Code`'s `cleaned_docs` output to `DocumentSplitter`'s `documents` input. - Connect `DocumentSplitter`'s `documents` output to `DeepsetNvidiaDocumentEmbedder`'s `documents` input. - Connect `DeepsetNvidiaDocumentEmbedder`'s `embeddings` output to `DocumentWriter`'s `documents` input. - Connect `DocumentWriter`'s `documents` output to `DocumentStore`'s `documents` input. - Connect `DocumentStore`'s `document_store` input to `OpenSearchDocumentStore`'s `document_store` output. This is what your index should look like: 9. Save and enable the index.
Click to view the complete index configuration ```yaml components: Code: type: deepset_cloud_custom_nodes.code.code_component.Code init_parameters: code: "from haystack import component, Document\nimport re\nfrom typing import List\n\n@component\nclass Code:\n \"\"\"\n Masks personally identifiable information in CV text before LLM processing.\n \"\"\"\n @component.output_types(cleaned_docs=List[Document])\n def run(self, documents: List[Document]) -> dict:\n cleaned_docs = []\n \n for doc in documents:\n redacted = doc.content\n\n # Email addresses\n email_pattern = r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b'\n redacted = re.sub(email_pattern, '[EMAIL]', redacted)\n\n # LinkedIn URLs\n linkedin_pattern = r'linkedin\\.com/in/[A-Za-z0-9_-]+'\n redacted = re.sub(linkedin_pattern, '[LINKEDIN]', redacted, flags=re.IGNORECASE)\n\n # GitHub URLs\n github_pattern = r'github\\.com/[A-Za-z0-9_-]+'\n redacted = re.sub(github_pattern, '[GITHUB]', redacted, flags=re.IGNORECASE)\n\n # Phone numbers: +44 7700 112233, 07700 112233, 798072811, etc.\n phone_pattern = r'(\\+\\d{1,3}[\\s.-]?)?\\(?\\d{2,4}\\)?[\\s.-]?\\d{3,4}[\\s.-]?\\d{3,4}|\\b\\d{9,11}\\b'\n redacted = re.sub(phone_pattern, '[PHONE]', redacted)\n\n # UK postcodes: BS8 1AF, M1 4HE, EC1A 1BB\n postcode_pattern = r'\\b[A-Z]{1,2}\\d[A-Z\\d]?\\s?\\d[A-Z]{2}\\b'\n redacted = re.sub(postcode_pattern, '[POSTCODE]', redacted, flags=re.IGNORECASE)\n\n # Street addresses (line containing number + street type)\n street_pattern = r'\\d+\\s+[\\w\\s]+(?:Street|St|Road|Rd|Avenue|Ave|Lane|Ln|Drive|Dr|Way|Court|Ct|Place|Pl|Square|Sq|Close|Crescent|Terrace|Grove|Park|Gardens|Row|Mews|Hill|Green|Wood|Gate|Walk|Fields|Rise|View|Valley|Meadow|Heights)\\b[^,\\n]*'\n redacted = re.sub(street_pattern, '[ADDRESS]', redacted, flags=re.IGNORECASE)\n\n # Date of birth patterns: DOB: 15/03/1988, Date of Birth: 15 March 1988\n dob_pattern = r'(DOB|Date of Birth|Born|Birthday|D\\.O\\.B\\.?)[\\s:]*\\d{1,2}[\\s./-](\\d{1,2}|Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)[\\s./-]\\d{2,4}'\n redacted = re.sub(dob_pattern, '[DATE_OF_BIRTH]', redacted, flags=re.IGNORECASE)\n\n # National Insurance Number (UK): AB 12 34 56 C\n nino_pattern = r'\\b[A-Z]{2}\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-Z]\\b'\n redacted = re.sub(nino_pattern, '[NATIONAL_ID]', redacted, flags=re.IGNORECASE)\n\n cleaned_docs.append(Document(content=redacted, meta=doc.meta))\n\n return {\"cleaned_docs\": cleaned_docs}" PDFMinerToDocument: type: haystack.components.converters.pdfminer.PDFMinerToDocument init_parameters: line_overlap: 0.5 char_margin: 2 line_margin: 0.5 word_margin: 0.1 boxes_flow: 0.5 detect_vertical: true all_texts: false store_full_path: false DocumentSplitter: type: haystack.components.preprocessors.document_splitter.DocumentSplitter init_parameters: split_by: word split_length: 200 split_overlap: 0 split_threshold: 0 splitting_function: respect_sentence_boundary: false language: en use_split_rules: true extend_abbreviations: true skip_empty_documents: true DeepsetNvidiaDocumentEmbedder: type: deepset_cloud_custom_nodes.embedders.nvidia.document_embedder.DeepsetNvidiaDocumentEmbedder init_parameters: model: intfloat/multilingual-e5-base prefix: '' suffix: '' batch_size: 32 meta_fields_to_embed: embedding_separator: \n truncate: normalize_embeddings: true timeout: backend_kwargs: DocumentWriter: type: haystack.components.writers.document_writer.DocumentWriter init_parameters: policy: NONE document_store: type: haystack_integrations.document_stores.opensearch.document_store.OpenSearchDocumentStore init_parameters: hosts: index: '' max_chunk_bytes: 104857600 embedding_dim: 768 return_embedding: false method: mappings: settings: create_index: true http_auth: use_ssl: verify_certs: timeout: connections: # Defines how the components are connected - sender: PDFMinerToDocument.documents receiver: Code.documents - sender: Code.cleaned_docs receiver: DocumentSplitter.documents - sender: DocumentSplitter.documents receiver: DeepsetNvidiaDocumentEmbedder.documents - sender: DeepsetNvidiaDocumentEmbedder.documents receiver: DocumentWriter.documents inputs: # Define the inputs for your pipeline files: # This component will receive the files to index as input - PDFMinerToDocument.sources max_runs_per_component: 100 metadata: {} ```
**Result**: You have created an index that can process PDF files and masks sensitive personal information using custom code. The index is enabled and ready to process files. ## Index Files Now, let's upload sample files to the workspace and index them. 1. Download the sample files from the sample-cvs folder in Google Drive and unzip it to a location on your computer. You should have five PDF files. 2. In , go to **Files** and click **Upload Files**. 3. Choose the five PDF files you just downloaded and click **Upload**. 4. Wait until the upload finishes. You should have five PDF files in your workspace. 5. Go to **Indexes** and click your PII-masking-index. This opens the index details page where you can see it's indexing the files you uploaded. 6. Wait until the index status changes to *Indexed* and all the files show as *Indexed*. 7. Click **View** next to the first file and switch to the **Documents** tab. You should see the document produced from this file with the sensitive information masked. **Result**: Congratulations! You have created an index that can process PDF files and masks sensitive personal information using custom code. You've also learned how to use the `Code` component in your apps. --- ## Tutorial: Building a Robust RAG App Build a retrieval augmented generation (RAG) app running on your own data that can generate answers in a friendly and conversational tone. Learn how to test different prompts and insert them into your pipeline from Prompt Explorer. *** - **Level**: Basic - **Time to complete**: 10 minutes - **Prerequisites**: - You must be an Admin to complete this tutorial. - You must have an API key from an active OpenAI account as this pipeline uses the GPT model by OpenAI. You can also use a model from another provider. - **Goal**: After completing this tutorial, you will have built a RAG system that can answer questions about treating various diseases based on the documents from [Mayo Clinic](https://www.mayoclinic.org/diseases-conditions). This system will run on the data you provide to it to minimize the possibility of hallucinations. - **Keywords**: large language models, retrieval augmented generation, RAG, gpt, Prompt Explorer *** ## Create a Workspace We need a workspace to store our files and the generative pipeline. 1. Log in to . 2. In the upper left corner, click the name of the workspace, type _RAG_ as the workspace name, and click **Create**. **Result**: You have created a workspace called `RAG`, where you'll upload the Mayo Clinic files. ## Upload Files to Your Workspace 1. First, download the [mayoclinic.zip](https://drive.google.com/file/d/16Y14-niu3-2shMnRP6-bPYNVRSTcMtEb/view?usp=sharing) file and unpack it on your computer. (You can also use your own files.) 2. In , make sure you're in the _RAG_ workspace, and go to _Files>Upload Files_. 3. Open the folder you downloaded and unzipped in step 1, select all the files in it, and drag them to the Upload Files window. Click **Upload**. 4. Wait until the upload finishes. You should have 1096 files in your workspace. **Result**: Your files are in the `RAG` workspace and you can see them on the Files page. ## Connect Your OpenAI Account Once you connect to your OpenAI account, you can use OpenAI models without passing the API keys in the pipeline. 1. Click your profile icon in the top right corner and choose **Settings**. 2. Go to *Workspace>Integrations* and find OpenAI. 3. Next to OpenAI, click **Connect**, paste your OpenAI API key, and click **Submit**. **Result**: You're connected to your OpenAI account and can use OpenAI models in your pipelines. ## Create a Draft Pipeline Let's create a pipeline that will be a starting point for the generative question answering app: 1. In the navigation, go to **Pipeline Templates**. 2. Choose **Conversational**, find _RAG Chat_, hover your mouse over the template and click **Use Template**. 3. Type _RAG_ as the pipeline name and click **Create Pipeline**. You're redirected to Builder, where you can view and edit your pipeline. 4. Open the Issues panel at the bottom of the canvas. You can see one issue there: Pipeline index missing error. Click **Inspect** next to it to jump to the `OpenSearchDocumentStore` component that needs the index. 5. Choose the `standard-index` you previously created from the list on the component card. 6. To test your pipeline, click **Run Pipeline** above the `Input` component and type "what are the symptoms of the flu?". You should see the answer in the chat window. :::tip Changing the Model This pipeline uses the gpt-5.4 model by default. You can change the model on the `LLM` component card. Click the **Model** parameter and choose a different model from the list. Make sure the model provider is connected to your account. For help, see [Add Integrations](/docs/how-to-guides/managing-access/add-integrations.mdx). ::: 7. Click **Deploy**. Wait until the pipeline is deployed. **Result**: You now have an indexed RAG chat pipeline that generates answers based on your data. Your pipeline status is *Deployed*, and it's ready for use. Your pipeline is at the development service level. We recommend you test it before setting it to the production service level. ## Work on Your Prompt The default prompt makes the model act as a matter-of-fact technical expert, while we want our system to be friendly and empathetic. Let's experiment with different prompts to achieve this effect. 1. In the navigation, click **Prompt Explorer**. 2. Choose the _RAG_ pipeline (1) and _qa_llm (User Prompt)_ (2). The current prompt is shown in the Prompt Editor panel. 3. In the `Type your query here` field, ask some questions about treating medical conditions, such as: "I had my wisdom tooth removed, but my gum hurts and is swollen. What should I do?" The model generates an answer and provides its sources, which are the documents it's based on. 4. Now, let's try a different prompt. In Prompt Editor, change the prompt to adjust the tone of the answer. Replace "You are a technical expert." with "You are a friendly nurse." and add "Your answers are friendly, clear, and conversational.", like in the prompt below: ``` You are a friendly, empathetic nurse. You answer questions truthfully based on provided documents. Your answers are friendly, clear, and conversational. For each document check whether it is related to the question. Only use documents that are related to the question to answer it. Ignore documents that are not related to the question. If the answer exists in several documents, summarize them. Only answer based on the documents provided. Don't make things up. If the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'. These are the documents: {% for document in documents %} Document[{{ loop.index }}]: {{ document.content }} {% endfor %} Question: {{question}} Answer: ``` 5. Try the same query or experiment with other queries related to treating medical conditions. The answers should now be in a more empathetic and friendly tone. Here are some example questions you can ask: "I have been diagnosed with a wheat allergy, what do I do now?" "How do you treat swollen wrists?" "What is meningitis?" 6. Insert the updated prompt into your RAG pipeline. Click **Update** in Prompt Editor and confirm your action. This creates a new pipeline version with the updated prompt without deploying it or modifying the current draft. **Result**: You have tweaked your prompt to generate more friendly and conversational answers. You updated your pipeline with this prompt. ## Test the Pipeline Time to see your pipeline in action! 1. In the navigation, click **Playground** and make sure the _RAG_ pipeline is selected. 2. Try asking something like "my eyes hurt, what should I do?". 3. Once the answer is generated, check the sources to see if the answers are actually in the documents. You can also check the prompt by clicking the More Actions button next to the search result. **Congratulations!** You have built a generative question answering system that can answer questions about treating various diseases in a friendly and conversational tone. Your system also shows references to documents it based its answers on. ## What To Do Next Your pipeline is now a development pipeline. Once it's ready for production, change its service level to _Production_. You can do this on the Pipeline Details page shown after clicking a pipeline name. To learn more, see [Pipeline Service Levels](/docs/concepts/about-pipelines/about-pipelines.mdx#pipeline-service-levels). --- ## Tutorial: Building a RAG Chat App with MongoDB Atlas Document Store Learn how to build a chat system running on your data in MongoDB Atlas. *** - **Level**: Beginner - **Time to complete**: 20 minutes - **Prerequisites**: - A basic knowledge of pipelines and indexes in . For more information, see [Pipelines](/docs/concepts/about-pipelines/about-pipelines.mdx) and [Indexes](/docs/concepts/indexes/indexes.mdx). - Understanding of document stores. For details, see [Document Stores](/docs/concepts/document-stores/document-stores.mdx). - A workspace where you'll create the pipeline. For help, see [Quick Start Guide](/docs/getting-started/quick-start-guide.mdx). - OpenAI API key as this pipeline uses GPT-4o. For details on how to connect to OpenAI, see [Use OpenAI Models](/docs/how-to-guides/designing-your-pipeline/use-hosted-models-and-services/use-openai-models.mdx). - A MongoDB account with a cluster containing the `mflix` sample dataset. For help, see MongoDB Atlas documentation: - [Create an account](https://www.mongodb.com/docs/atlas/tutorial/create-atlas-account/) - [Deploy a free cluster](https://www.mongodb.com/docs/atlas/tutorial/deploy-free-tier-cluster/) - [Create a connection string](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/quick-start/create-a-connection-string/) - [Load sample data](https://www.mongodb.com/docs/atlas/sample-data/) - [Sample mflix dataset](https://www.mongodb.com/docs/atlas/sample-data/sample-mflix/) - **Goal**: After completing this tutorial, you will have built a chat application that runs on the sample movie dataset in MongoDB Atlas. It uses both full text search and semantic search to retrieve relevant documents. *** ## Connect to MongoDB Atlas You need the MongoDB Atlas connection string. 1. Log in to MongoDB Atlas and open your project overview. 2. In the _Application Development_ section click **Get connection string**, and copy the connection string in step 3. 3. Go to , click your profile icon in the top right corner, and choose _Settings_. 4. Go to *Workspace>Integrations* and find MongoDB. 5. Click **Connect** next to MongoDB. 5. Paste your MongoDB connections string replacing `db_password` with your database password and click **Connect**. **Result**: is connected to your MongoDB Atlas database, which means that can access data in your MongoDB Atlas database. ## Create a Search Index for Your MongoDB Collection ### Create Full Text Search Index First, create a full text search index for keyword searches. For details and other methods of creating the index, see [Atlas Search](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/atlas-search/) in MongoDB Atlas documentation. 1. In MongoDB Atlas, open your cluster, and click the **Atlas Search** tab. 2. Click **Create Search Index**. 3. Choose *Atlas Search* as the index type. 4. Type `text_index` as the index name. 5. Choose _embedded_movies_ as the collection. 6. Choose **Visual Editor** as the configuration method and click **Next**. 7. Click **Create Search Index**. **Result**: You have created a full text search index called `text_search`. It's listed under Atlas Search in your cluster view. You may need to wait a while until Atlas builds your index and its status changes to _Ready_. ### Add Field Mapping 1. On the _Atlas Search_ tab, click **More Actions** next to your text index and choose _Edit With Visual Editor_. 2. On the _Index Overview_ tab, scroll down to _Field Mappings_, and choose **Add Field Mapping**. 3. Find _Field Name_, choose _fullplot_, and click **Add**. 4. Save your settings. **Result**: You added `fullplot` as your index field. It's now showing under Index Fields in the Atlas Search tab. # Create a Vector Search Index Now, you'll create a vector search index for semantic searches. You can also follow MongoDB Atlas documentation on [Atlas Vector Search](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/vector-search/) to complete this step. 1. In MongoDB Atlas, on the _Atlas Search_ tab, click **CREATE SEARCH INDEX**. 2. Choose _Vector Search_ as its type. 3. Leave `vector_index` as the name. 4. Choose _embedded_movies_ as the collection. 5. Choose **Visual Editor **as the configuration method and click **Next**. 6. Make sure `plot_embedding` is chosen as the path of the Vector Field. 7. Choose the similarity method and click **Next**. 8. Review your vector index configuration and click **Create Vector Search Index**. **Result**: You have create a vector search index on the plot_embedding field. The index is listed under the Atlas Search tab. You may need to wait a while until Atlas builds it and the index is ready. ## Create a RAG Chat Application 1. In go to Pipeline Templates. 2. Choose the _Conversational_ category and find the _MongoDB Atlas RAG Chat_ template. 3. Hover over the template and click **Use Template**. 4. Leave the default name and click **Create Pipeline**. The template opens in Builder. You can see that it uses `MongoDBAtlasDocumentStore` as the document store. :::tip Changing the Model This pipeline uses the gpt-4o model by default. You can change the model on the `qa_llm` component card. Click the **Model** parameter and choose a different model from the list. You can also update the prompt here. ::: 5. In Builder, click **Deploy** and confirm. You can test a deployed pipeline in the Playground or share it with others to gather their feedback. **Result**: Congratulations! You have created a RAG chat application that uses gpt-4o and runs on the sample dataset in your MongoDB Atlas database. You can now try it out in Playground. For instructions, see [Testing Your Pipeline](/docs/how-to-guides/searching-with-your-pipeline/run-a-search.mdx). :::info Indexing status Since MongoDB Atlas is an external document store, you won't be able to view indexing status or see which files are part of your index. However, you can access the logs for insights into the indexing process. ::: --- ## Tutorial: Building Your First Document Search App This tutorial teaches you how to build a document search system in the easiest and fastest possible way. It uses the UI for uploading the sample files and a template for creating the document retrieval pipeline. *** - **Level**: Beginner - **Time to complete**: 10 minutes - **Prerequisites**: - This tutorial assumes a basic knowledge of language models. - You must be an Admin to complete this tutorial. - Make sure you have a workspace where the information retrieval pipeline will run. - **Goal**: After completing this tutorial, you will have built a complete English document retrieval system from scratch that can fetch NHS documents. *** ## Upload Files First, let's get the files the search will run on into . 1. Download the .zip file from gdrive and unzip it to a location on your computer. 2. Log in to , switch to the right workspace, and go to _Files_. 3. Click **Upload Files**, drag the files you unpacked in step 1, and drop them to the Upload Files window. (You must select all files in a folder; doesn't support uploading folders.) 4. Click **Upload** and wait until the upload finishes. Even when the upload is finished, the files may take a while to show up in . That's expected; just wait a while and refresh the page if needed. **Result**: Your files have been uploaded and are shown on the Files page. You should have 953 files. ## Create a Pipeline The next step is to define the components of your search app. We'll use a document search pipeline template with a vector retriever to create the pipeline. 1. In the navigation, go to **Pipeline Templates**. 2. Choose _Document Search_ as the category, find _Semantic Document Search_, and click **Use Template**. 3. Type _NHS_doc_search_ as the pipeline name and click **Create Pipeline**. You're redirected to Builder. 4. Open the Issues panel at the bottom of the canvas. You can see one issue there: Pipeline index missing error. Click **Inspect** next to it to jump to the component that needs the index. 5. On the `OpenSearchDocumentStore` component card, choose the `standard-index` you previously created from the list. 6. To quickly test your pipeline, zoom in, click **Run Pipeline** above the `Input` component and type "How do I treat atopic skin?". You should see the results in the chat window. **Result**: You created a pipeline with an index, which means your documents have been indexed, and you can now run searches on them. Your pipeline is at the development service level. Let's test it. ## Test Your Pipeline Before testing your pipeline, deploy it first. Click **Deploy** in the upper right corner of Builder. Wait until your pipeline status changes to *Deployed*. When your pipeline is deployed: 1. In Builder, click **Playground**. 2. Choose _Current draft_ as the pipeline version. 3. Type queries related to health and check the documents retrieved. You can check the logs to see the retrieved documents. 4. To share your pipeline with others: 1. Click **Deploy** and choose the version to deploy. 2. Once the pipeline is deployed, you'll see the **Share** button in Playground. 3. Click **Share** and configure the settings for the shared pipeline. Sharing creates a link to the pipeline chat view that others can access and try without creating an account. For more information, see [Share a Pipeline Prototype](/docs/how-to-guides/evaluating-your-pipeline/share-a-pipeline-prototype.mdx). **Result**: Congratulations! You have built a search system that can retrieve documents related to health. You can now ask health-related queries, and it will find relevant documents. ## What's Next Your pipeline is now a development pipeline. Once it's ready for production, change its service level to _Production_. You can do this on the Pipeline Details page shown after clicking a pipeline name. To learn more, see [Pipeline Service Levels](/docs/concepts/about-pipelines/about-pipelines.mdx#pipeline-service-levels). --- ## Tutorial: Integrating Haystack Enterprise Platform API with Your Frontend App # Tutorial: Integrating API with Your Frontend App Connect your frontend app to a RAG pipeline deployed on . We've prepared an example Next.js UI you can use in this tutorial. The UI is inspired by the Playground feature in and you can use it to query your pipeline, and display its answers and references. *** - **Level**: Basic - **Time to complete**: 10 minutes - **Prerequisites**: - An indexed RAG pipeline deployed in . To display references for your pipeline's answers, it must contain appropriate instructions in the prompt and have the `DeepsetAnswerBuilder` component with reference pattern set to `acm`. For detailed instruction, see [Enable References for Generated Answers](/docs/how-to-guides/designing-your-pipeline/work-with-llms/enable-references-for-generated-answers.mdx) - Data for your pipeline to query uploaded to the same workspace as your pipeline. For help, see [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). - A API key. For instructions, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). - Basic knowledge of GitHub repositories. - You can use the UI we prepared as is, but to modify it, a basic knowledge of Next.js is helpful. - **Description**: This tutorial shows how to connect to an UI we've prepared. This UI is meant to serve as an example and may not include all necessary security measures and features required for a full production environment. You can use it as a starting point. Here's what it looks like out of the box: - **Goal**: After completing this tutorial, you will have a locally deployed user interface to query your RAG pipeline. The UI shows answers and references. *** ## Test Your Pipeline First, let's check if your pipeline is ready and your API key is working. In the following code sample, replace: - `YOUR_WORKSPACE_NAME` with the name of the workspace where you created your pipeline - `YOUR_RAG_PIPELINE_NAME` with the name of your RAG pipeline - `YOUR_API_KEY` with the API key - `Your query` with a query your pipeline can answer Use this code to test your pipeline: ```shell curl \ --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/YOUR_WORKSPACE_NAME/pipelines/YOUR_RAG_PIPELINE_NAME/search \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --header 'authorization: Bearer YOUR_API_KEY' \ --data '{ "debug": false, "view_prompts": false, "queries": ["Your query" ] }'| \ less ``` You should get a paginated response with an answer to the query. ## Run Dev Server to Test the UI Locally 1. Clone the [GitHub repository](https://github.com/deepset-ai/rag-ui-nextjs). 2. In the command line, navigate to the location where you cloned the repository. 3. In this location, create a file called _.env.local_ with the following contents: ``` DEEPSET_CLOUD_WORKSPACE=YOUR_WORKSPACE_NAME DEEPSET_CLOUD_PIPELINE=YOUR_RAG_PIPELINE_NAME DEEPSET_CLOUD_API_KEY=YOUR_API_KEY ``` 4. Install dependencies: ```shell npm install ``` 5. Start the development server: ```shell npm run dev ``` 6. In your browser, open `http://localhost:3000` to see the UI. You should be able to ask questions and get answers. If you instructed the LLM to add references, you'll also see them in the generated answers. 7. When you're done testing, stop the server with Ctrl+C. --- ## Tutorial: Uploading Files with Metadata through SDK CLI Learn to quickly upload large amounts of files with metadata. In this tutorial, you'll upload a set of hotel reviews but you can replace these files with your own. You will use the SDK package with a command-line. *** - **Level**: Beginner - **Time to complete**: 10 minutes - **Prerequisites**: - You must be an Admin to complete this tutorial. - The workspace where you want to upload the files must already be created in . In this tutorial, we call the workspace _hotel_reviews_. - **Goal**: After completing this tutorial, you will have uploaded a set of hotel reviews with metadata to a workspace. You can replace this dataset with your custom one. *** ## Prepare Your Files This tutorial uses a set of hotel reviews with some metadata in them. You can also use your own files. Make sure their extensions are lowercase, for example: _myfile.txt_ instead of _myfile.TXT_. 1. Download [the hotel reviews dataset](https://drive.google.com/file/d/1T4ngb51UYIUIU1HVvEe4DzDzt4By0xSl/view?usp=sharing). 2. Extract the files to a folder called _hotel_reviews_ in your _Documents_ folder. This can take a couple of minutes. **Result**: You have 5,956 files in the _\\Documents\\hotel_reviews_ folder, 2978 TXT files and 2978 JSON files. Each TXT file is accompanied by a `.meta.json` file containing the text file metadata. ## Install the SDK 1. Open the command line and run: ```powershell terminal pip install deepset-cloud-sdk ``` 2. Wait until the installation finishes with a success message. **Result**: You have installed the SDK. It comes with a command line interface that we'll use to upload the files. ## Obtain the API Key 1. Log in to [](https://cloud.deepset.ai/). 2. Click your profile icon in the top right corner and choose _Settings_. 3. Go to *Workspace>API Keys*. 4. Under API Keys, click **Create API key**. 5. Configure the key: 1. Choose Personal Key. 2. Type "tutorial" as the key name. 3. Set the expiration date to the end of the month. 4. Choose the workspace where you want to upload the files. 5. Choose the role to determine the key's permissions. It should be at least Editor. 6. Click **Create API key**. 6. Copy the key and save it to a notepad. **Result**: You have an API key saved in a file. You can now use it to upload your files. ## Upload Files 1. Open the command line and run the following command to log in to : ```python MacOS deepset-cloud login ``` ```python Windows python -m deepset_cloud_sdk.cli login ``` 2. When prompted, paste your API key. 3. Type the name of the workspace where you want to upload the files. This creates an _.env_ file with the information you just provided. The SDK uses the information from this file when uploading files. 4. Run this command to upload files, including all the subfolders of the _hotel_reviews_ folder and overwrite any files with the same name that might already exist in the workspace: ```python MacOS deepset-cloud upload --recursive --write-mode OVERWRITE ``` ```python Windows python -m deepset_cloud_sdk.cli upload --recursive --write-mode OVERWRITE ``` :::info Uploading other file types To upload other file types, use `--desired_file_types` with a list of file types, for example: `--desired_file_types ['.csv', '.html']\`. ::: 5. Wait until the upload finishes successfully. You should see this message: 5956 files are uploaded, and half of them, 2978 are listed in . (The metadata files are not shown in ). **Result**: You have uploaded all your files, including the ones from the subfolders. Let's now see if they're showing up in . ## Verify the Upload - In the command line, list the uploaded files by running: ```python MacOS deepset-cloud list-files ``` ```python Windows python -m deepset_cloud_sdk.cli list-files ``` You should see a list of files with file ID, URL, name, size, metadata, and the date when it was created. With the number of files we uploaded, it's easier to verify if they uploaded correctly in the UI. - You can also check it in . Click the workspace name to switch to the workspace where you uploaded the files, and choose **Files** in the navigation. You should see all the uploaded files on the Files page. - Now, let's check if the metadata was uploaded. One way to do this is to open a random file and then click **View Metadata** on the file preview. --- ## Tutorial: Managing Feedback Entries Through REST API Learn to add, update, and delete feedback entries using REST API endpoints. *** - **Level**: Basic - **Time to complete**: 10 minutes - **Prerequisites**: - You must have a basic understanding of REST API: HTTP methods, response and request structure, and basic concepts. - Basic programming knowledge is a plus. - You must have a API key. For instructions, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). - You must have a pipeline and some files in your workspace. (You can use the sample files we provide). For help, see [Create a Pipeline](/docs/how-to-guides/designing-your-pipeline/create-a-pipeline/create-a-pipeline-in-studio.mdx) and [Upload Files](/docs/how-to-guides/working-with-your-data/upload-files.mdx). - **Goal**: After completing this tutorial, you will know how to add, update, and delete feedback for your pipeline's answers using the REST API. *** ## Get Pipeline and Workspace IDs The feedback API uses workspace and pipeline IDs to identify them. ## Run a Search on Your Pipeline Ask a query to get a response you can then give feedback on. Use the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post) endpoint. You can use this code sample (cURL or Python) as a starting point. In the URL, replace: - `YOUR_WORKSPACE_NAME` with the name of the workspace containing the pipeline. - `YOUR_PIPELINE_NAME` with the name of the pipeline you want to run the search with. In `header`, replace `DEEPSET_API_KEY` with your API key. ```python url = "https://api.cloud.deepset.ai/api/v1/workspaces//pipelines//search" payload = { "debug": False, "view_prompts": False, "queries": ["what are the symptomps of milk allegry?"] } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer " } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces//pipelines//search \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data ' { "debug": false, "view_prompts": false, "queries": [ "what are the symptomps of milk allegry?" ] } ' ``` The response contains the query and the result ID, which you'll need to add, update, or delete feedback entries. :::info Finding the Correct Result and Query IDs To add a feedback entry, you’ll need the result ID associated with the answer. In the example response below, the result ID is `7e07bd73-c099-44fe-9d65-ec0ba5e83c41`. Keep in mind that each document also has its own result ID. Make sure to use the result ID from the answer itself when adding your feedback. For the query ID, make sure to use the query ID located in the `results` object. In the example below, it's `37547edb-48ec-49c0-96e8-1fcb5f37bd0c`. :::
Sample response ```json { "query_id": "37547edb-48ec-49c0-96e8-1fcb5f37bd0c", "results": [ { "query_id": "37547edb-48ec-49c0-96e8-1fcb5f37bd0c", "query": "What are milk allergy symptomps?", "answers": [ { "answer": "Milk allergy symptoms can be immediate or take more time to develop. Immediate signs and symptoms of milk allergy might include:\n\n* Hives\n* Wheezing\n* Itching or tingling feeling around the lips or mouth\n* Swelling of the lips, tongue or throat\n* Coughing or shortness of breath\n* Vomiting\n\nSigns and symptoms that may take more time to develop include:\n\n* Loose stools or diarrhea, which may contain blood\n* Abdominal cramps\n* Runny nose\n* Watery eyes\n* Colic, in babies\n\nAdditionally, mentions some general allergy symptoms that may also apply to milk allergy, including:\n\n* Itchy, irritated skin\n* Nasal stuffiness (congestion)\n* Belly (abdominal) pain\n* Dizziness, lightheadedness or fainting\n\nNote that is not specifically about milk allergy, but about allergies in general. However, the symptoms listed may still be relevant to milk allergy.", "type": "generative", "score": null, "context": null, "offsets_in_document": [], "offsets_in_context": [], "document_id": null, "document_ids": [ "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902", "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293", "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31", "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525", "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba", "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7" ], "meta": { "_references": [ { "answer_end_idx": 13, "answer_start_idx": 13, "document_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "document_position": 1, "label": "grounded", "score": 0, "doc_end_idx": 1559, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 18, "answer_start_idx": 18, "document_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "document_position": 2, "label": "grounded", "score": 0, "doc_end_idx": 1402, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 507, "answer_start_idx": 507, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "document_position": 8, "label": "grounded", "score": 0, "doc_end_idx": 1576, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 729, "answer_start_idx": 729, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "document_position": 8, "label": "grounded", "score": 0, "doc_end_idx": 1576, "doc_start_idx": 0, "origin": "llm" } ] }, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "files": [ { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" } ], "result_id": "7e07bd73-c099-44fe-9d65-ec0ba5e83c41", /* the result ID you'll need */ "prompt": "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nYou answer questions truthfully based on provided documents.\nFor each document check whether it is related to the question.\nOnly use documents that are related to the question to answer it.\nIgnore documents that are not related to the question.\nIf the answer exists in several documents, summarize them.\nOnly answer based on the documents provided. Don't make things up.\nIf the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'.\nAlways use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3].\nNever name the documents, only enter a number in square brackets as a reference.\nThe reference must only refer to the number that comes in square brackets after the document.\nOtherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\nThese are the documents:\n\nDocument[1]:\nOverview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n\n\nDocument[2]:\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. \n\nDocument[3]:\nTests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n\n\nDocument[4]:\nThe next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. \n\nDocument[5]:\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. \n\nDocument[6]:\nSoy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.\n\nDocument[7]:\nDoes your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. \n\nDocument[8]:\nThey may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. \n\nQuestion: What are milk allergy symptomps? <|eot_id|><|start_header_id|>assistant<|end_header_id|>" } ], "documents": [ { "id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "content": "Overview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 0, 633 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" } ], "split_idx_start": 0, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 0, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.76318359375, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "bc8173bd-0164-4668-999d-ab579681077a" }, { "id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "content": "Immediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 926, 1559 ], "doc_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6" }, { "range": [ 0, 254 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" } ], "split_idx_start": 926, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 1, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.6025390625, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "8c702ffb-9170-4b8d-a5f4-6a35a6b2ff36" }, { "id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902", "content": "Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1148, 1402 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" }, { "range": [ 0, 224 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" } ], "split_idx_start": 2074, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 2, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.1593017578125, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "b4e68189-dfb3-4fa3-a987-28529dfbba05" }, { "id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293", "content": "The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1060, 1284 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" }, { "range": [ 0, 230 ], "doc_id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31" } ], "split_idx_start": 3134, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 3, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.1376953125, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "774c03b5-87ee-453d-9ca4-7688a8f70335" }, { "id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31", "content": "Risk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1198, 1428 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" }, { "range": [ 0, 236 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" } ], "split_idx_start": 4332, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 4, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.05224609375, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "b304143d-5c83-40be-b9f3-422fee1e9952" }, { "id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525", "content": "Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1297, 1585 ], "doc_id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba" } ], "split_idx_start": 8221, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 7, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.051666259765625, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "9c033d90-a592-46aa-976f-d884047a1a6e" }, { "id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba", "content": "Does your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1324, 1561 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" }, { "range": [ 0, 288 ], "doc_id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525" } ], "split_idx_start": 6924, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 6, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.0341796875, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "1b5869e2-0233-4255-a875-65748b4151b9" }, { "id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "content": "They may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 977, 1585 ], "doc_id": "9b92616ee62b77dd44659f9b3589516d24587eea08bddc375bc2dc7fc6deb84a" }, { "range": [ 0, 676 ], "doc_id": "c894391a5e0feafe8251959fc0aa0942cf95bc085998374c9936ad693e00e979" } ], "split_idx_start": 977, "file_name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 1, "dataset_name": "Healthcare", "_file_size": 9017, "page_number": 1, "source_id": "35308e27d89136421775a7c1d7e7c709e7b938ebff990548bcdd383940031f4c" }, "score": 0.026763916015625, "embedding": null, "file": { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" }, "result_id": "bfc1a187-4654-48d6-9339-2b81dbe4f5b2" } ], "_debug": null, "prompts": null } ] } ```
## Add, Update, and Delete Feedback ### Add a Feedback Entry Add feedback to an answer your pipeline returned. Use the [Create Feedback](/docs/api/main/create-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-post) endpoint. You can assign one of the feedback scores: - `ACCURATE` (corresponds to the thumbs up icon in the UI) - `INACCURATE` (corresponds to the thumbs down icon in the UI) - `FAIRLY_ACCURATE` (corresponds to the mixed/neutral icon in the UI) You need the following IDs to make the request: #### Query ID 1. Click **Pipelines**, find the pipeline that was used to answer the query, and click its name. This opens the Pipeline Details page. 2. Click **Search History**. 3. Find the query you want to add feedback for and click Details next to it. You'll find the query ID in the expanded panel. #### Result ID You can get it from the [Search](/docs/api/main/search-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-post) endpoint. To add a feedback entry, you can use this code replacing the IDs and your API key: ```python url = "https://api.cloud.deepset.ai/api/v2/workspaces//pipelines//feedback" payload = { "query_id": "", "result_id": "", "score": "" } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer " } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v2/workspaces//pipelines//feedback \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data ' { "query_id": "", "result_id": "", "score": "" } ' ``` The response includes the feedback ID, which you will need to update or delete the feedback entry.
Sample response ```json { "score": "ACCURATE", "comment": null, "bookmarked": false, "tags": [], "result_id": "7e07bd73-c099-44fe-9d65-ec0ba5e83c41", "feedback_id": "2fcba96d-8ae3-4572-af4c-47a9aed536a7", /*this is the feedback ID*/ "organization_id": "4f26a3b2-03fc-4742-a4b1-8c3dae2b2d2a", "workspace_id": "b7f048eb-7b48-4ad8-b7b0-443cdddb81c5", "pipeline_id": "07b04f1a-e053-4bd1-b3d5-e740b0dd6f2d", "created_by": { "user_id": "f6398740-5555-445d-8ae3-ef980ea4191d", "given_name": "Jane", "family_name": "Smith" }, "created_at": "2024-12-10T11:56:13.884352Z", "search_history": { "search_history_result_id": "7e07bd73-c099-44fe-9d65-ec0ba5e83c41", "query_id": "37547edb-48ec-49c0-96e8-1fcb5f37bd0c", "documents": [ { "id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "content": "Overview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 0, 633 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" } ], "split_idx_start": 0, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 0, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.76318359375, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "bc8173bd-0164-4668-999d-ab579681077a" }, { "id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "content": "Immediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 926, 1559 ], "doc_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6" }, { "range": [ 0, 254 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" } ], "split_idx_start": 926, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 1, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.6025390625, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "8c702ffb-9170-4b8d-a5f4-6a35a6b2ff36" }, { "id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902", "content": "Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1148, 1402 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" }, { "range": [ 0, 224 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" } ], "split_idx_start": 2074, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 2, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.1593017578125, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "b4e68189-dfb3-4fa3-a987-28529dfbba05" }, { "id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293", "content": "The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1060, 1284 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" }, { "range": [ 0, 230 ], "doc_id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31" } ], "split_idx_start": 3134, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 3, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.1376953125, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "774c03b5-87ee-453d-9ca4-7688a8f70335" }, { "id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31", "content": "Risk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1198, 1428 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" }, { "range": [ 0, 236 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" } ], "split_idx_start": 4332, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 4, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.05224609375, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "b304143d-5c83-40be-b9f3-422fee1e9952" }, { "id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525", "content": "Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1297, 1585 ], "doc_id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba" } ], "split_idx_start": 8221, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 7, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.051666259765625, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "9c033d90-a592-46aa-976f-d884047a1a6e" }, { "id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba", "content": "Does your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1324, 1561 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" }, { "range": [ 0, 288 ], "doc_id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525" } ], "split_idx_start": 6924, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 6, "dataset_name": "Healthcare", "_file_size": 4962, "page_number": 1, "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e" }, "score": 0.0341796875, "embedding": null, "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "result_id": "1b5869e2-0233-4255-a875-65748b4151b9" }, { "id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "content": "They may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 977, 1585 ], "doc_id": "9b92616ee62b77dd44659f9b3589516d24587eea08bddc375bc2dc7fc6deb84a" }, { "range": [ 0, 676 ], "doc_id": "c894391a5e0feafe8251959fc0aa0942cf95bc085998374c9936ad693e00e979" } ], "split_idx_start": 977, "file_name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt", "_file_created_at": "2024-12-09T11:08:47.728733+00:00", "split_id": 1, "dataset_name": "Healthcare", "_file_size": 9017, "page_number": 1, "source_id": "35308e27d89136421775a7c1d7e7c709e7b938ebff990548bcdd383940031f4c" }, "score": 0.026763916015625, "embedding": null, "file": { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" }, "result_id": "bfc1a187-4654-48d6-9339-2b81dbe4f5b2" } ], "type": "generative", "rank": 1, "score": null, "files": [ { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" } ], "context": null, "answer": "According to and , milk allergy symptoms can be immediate or take more time to develop. Immediate signs and symptoms of milk allergy might include:\n\n* Hives\n* Wheezing\n* Itching or tingling feeling around the lips or mouth\n* Swelling of the lips, tongue or throat\n* Coughing or shortness of breath\n* Vomiting\n\nSigns and symptoms that may take more time to develop include:\n\n* Loose stools or diarrhea, which may contain blood\n* Abdominal cramps\n* Runny nose\n* Watery eyes\n* Colic, in babies\n\nAdditionally, mentions some general allergy symptoms that may also apply to milk allergy, including:\n\n* Itchy, irritated skin\n* Nasal stuffiness (congestion)\n* Belly (abdominal) pain\n* Dizziness, lightheadedness or fainting\n\nNote that is not specifically about milk allergy, but about allergies in general. However, the symptoms listed may still be relevant to milk allergy.", "meta": { "_references": [ { "answer_end_idx": 13, "answer_start_idx": 13, "document_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "document_position": 1, "label": "grounded", "score": 0, "doc_end_idx": 1559, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 18, "answer_start_idx": 18, "document_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "document_position": 2, "label": "grounded", "score": 0, "doc_end_idx": 1402, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 507, "answer_start_idx": 507, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "document_position": 8, "label": "grounded", "score": 0, "doc_end_idx": 1576, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 729, "answer_start_idx": 729, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "document_position": 8, "label": "grounded", "score": 0, "doc_end_idx": 1576, "doc_start_idx": 0, "origin": "llm" } ] }, "offsets_in_context": [], "prompt": "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nYou answer questions truthfully based on provided documents.\nFor each document check whether it is related to the question.\nOnly use documents that are related to the question to answer it.\nIgnore documents that are not related to the question.\nIf the answer exists in several documents, summarize them.\nOnly answer based on the documents provided. Don't make things up.\nIf the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'.\nAlways use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3].\nNever name the documents, only enter a number in square brackets as a reference.\nThe reference must only refer to the number that comes in square brackets after the document.\nOtherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\nThese are the documents:\n\nDocument[1]:\nOverview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n\n\nDocument[2]:\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. \n\nDocument[3]:\nTests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n\n\nDocument[4]:\nThe next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. \n\nDocument[5]:\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. \n\nDocument[6]:\nSoy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.\n\nDocument[7]:\nDoes your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. \n\nDocument[8]:\nThey may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. \n\nQuestion: What are milk allergy symptomps? <|eot_id|><|start_header_id|>assistant<|end_header_id|>", "search": { "created_at": "2024-12-09T12:33:30.371439Z", "duration": 19.983364582061768, "query": "What are milk allergy symptomps?", "filters": {} } } } ```
### Update Feedback You can always update the feedback you gave earlier using the [Update Feedback](/docs/api/main/update-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-feedback-id-patch) endpoint. You need the following IDs for this: - Workspace ID (you can check it in the *Settings > Workspace > General* page.) - Pipeline ID (you can check it in the on the *Pipeline Details* page.) - Feedback ID (from the [Create Feedback](/docs/api/main/create-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-post) endpoint) Here is the code you can use to update a feedback entry. Make sure you replace workspace, pipeline, and feedback IDs in the URL and API key in headers. Pass the new feedback score in payload: ```python url = "https://api.cloud.deepset.ai/api/v2/workspaces//pipelines//feedback/" payload = { "score": "ACCURATE" } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer " } response = requests.patch(url, json=payload, headers=headers) print(response.text) ``` ```curl curl --request PATCH \ --url https://api.cloud.deepset.ai/api/v2/workspaces/WORKSPACE_ID/pipelines/PIPELINE_ID/feedback/FEEDBACK_ID \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data '{"score":"ACCURATE"}' ```
Sample response ```json { "score": "FAIRLY_ACCURATE", /*the updated score*/ "comment": null, "bookmarked": false, "tags": [], "result_id": "7e07bd73-c099-44fe-9d65-ec0ba5e83c41", "feedback_id": "2fcba96d-8ae3-4572-af4c-47a9aed536a7", "organization_id": "4f26a3b2-03fc-4742-a4b1-8c3dae2b2d2a", "workspace_id": "b7f048eb-7b48-4ad8-b7b0-443cdddb81c5", "pipeline_id": "07b04f1a-e053-4bd1-b3d5-e740b0dd6f2d", "created_by": { "user_id": "f6398740-5555-445d-8ae3-ef980ea4191d", "given_name": "Agnieszka", "family_name": "Marzec" }, "created_at": "2024-12-10T11:56:13.884352Z", "search_history": { "search_history_result_id": "7e07bd73-c099-44fe-9d65-ec0ba5e83c41", "query_id": "37547edb-48ec-49c0-96e8-1fcb5f37bd0c", "documents": [ { "id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 0, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 0, 633 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" } ], "split_idx_start": 0, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.76318359375, "content": "Overview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n", "embedding": null, "result_id": "bc8173bd-0164-4668-999d-ab579681077a", "content_type": "text" }, { "id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 1, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 926, 1559 ], "doc_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6" }, { "range": [ 0, 254 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" } ], "split_idx_start": 926, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.6025390625, "content": "Immediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. ", "embedding": null, "result_id": "8c702ffb-9170-4b8d-a5f4-6a35a6b2ff36", "content_type": "text" }, { "id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 2, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 1148, 1402 ], "doc_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61" }, { "range": [ 0, 224 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" } ], "split_idx_start": 2074, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.1593017578125, "content": "Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n", "embedding": null, "result_id": "b4e68189-dfb3-4fa3-a987-28529dfbba05", "content_type": "text" }, { "id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 3, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 1060, 1284 ], "doc_id": "13a4046915e3b7f1ddce5cb4a69494da53972863c2a93470a9bd579787a76902" }, { "range": [ 0, 230 ], "doc_id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31" } ], "split_idx_start": 3134, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.1376953125, "content": "The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. ", "embedding": null, "result_id": "774c03b5-87ee-453d-9ca4-7688a8f70335", "content_type": "text" }, { "id": "cf0faa27a97156c1fcd25b1970bf77c407267a8110cb5143482e980ba6438e31", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 4, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 1198, 1428 ], "doc_id": "01374947009de69505ab48ce77aff8579c75986101ed3e2b16c9a637b576e293" }, { "range": [ 0, 236 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" } ], "split_idx_start": 4332, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.05224609375, "content": "Risk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. ", "embedding": null, "result_id": "b304143d-5c83-40be-b9f3-422fee1e9952", "content_type": "text" }, { "id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 7, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 1297, 1585 ], "doc_id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba" } ], "split_idx_start": 8221, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.051666259765625, "content": "Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.", "embedding": null, "result_id": "9c033d90-a592-46aa-976f-d884047a1a6e", "content_type": "text" }, { "id": "e81e29ab84fd3d190876a323afb80cffa291c18a54b19e735ae96056346432ba", "file": { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, "meta": { "split_id": 6, "file_name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt", "source_id": "95731bef674bd1f778c2b8ffa3de3eddf9eaf1d0b3dd33567287780041ab517e", "_file_size": 4962, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 1324, 1561 ], "doc_id": "f7571820008fb10ef49414199539bbdffc6dc28cbdaf775a63cd05ae00a6d155" }, { "range": [ 0, 288 ], "doc_id": "0813ca29e002b219399bdbbf8ec1ad4a82f206e67e29126d5cdd7639b9894525" } ], "split_idx_start": 6924, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.0341796875, "content": "Does your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. ", "embedding": null, "result_id": "1b5869e2-0233-4255-a875-65748b4151b9", "content_type": "text" }, { "id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "file": { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" }, "meta": { "split_id": 1, "file_name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt", "source_id": "35308e27d89136421775a7c1d7e7c709e7b938ebff990548bcdd383940031f4c", "_file_size": 9017, "page_number": 1, "dataset_name": "Healthcare", "_split_overlap": [ { "range": [ 977, 1585 ], "doc_id": "9b92616ee62b77dd44659f9b3589516d24587eea08bddc375bc2dc7fc6deb84a" }, { "range": [ 0, 676 ], "doc_id": "c894391a5e0feafe8251959fc0aa0942cf95bc085998374c9936ad693e00e979" } ], "split_idx_start": 977, "_file_created_at": "2024-12-09T11:08:47.728733+00:00" }, "score": 0.026763916015625, "content": "They may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. ", "embedding": null, "result_id": "bfc1a187-4654-48d6-9339-2b81dbe4f5b2", "content_type": "text" } ], "type": "generative", "rank": 1, "score": null, "files": [ { "id": "c83a91f9-6206-478d-8838-938431ccd410", "name": "https___www.mayoclinic.org_diseases-conditions_milk-allergy_symptoms-causes_syc-20375101_3d1d6c.txt" }, { "id": "04d06fa7-c3ef-4a7d-9244-55c83924e230", "name": "https___www.mayoclinic.org_diseases-conditions_shellfish-allergy_symptoms-causes_syc-20377503_63c3a1.txt" } ], "context": null, "answer": "According to and , milk allergy symptoms can be immediate or take more time to develop. Immediate signs and symptoms of milk allergy might include:\n\n* Hives\n* Wheezing\n* Itching or tingling feeling around the lips or mouth\n* Swelling of the lips, tongue or throat\n* Coughing or shortness of breath\n* Vomiting\n\nSigns and symptoms that may take more time to develop include:\n\n* Loose stools or diarrhea, which may contain blood\n* Abdominal cramps\n* Runny nose\n* Watery eyes\n* Colic, in babies\n\nAdditionally, mentions some general allergy symptoms that may also apply to milk allergy, including:\n\n* Itchy, irritated skin\n* Nasal stuffiness (congestion)\n* Belly (abdominal) pain\n* Dizziness, lightheadedness or fainting\n\nNote that is not specifically about milk allergy, but about allergies in general. However, the symptoms listed may still be relevant to milk allergy.", "meta": { "_references": [ { "label": "grounded", "score": 0, "origin": "llm", "doc_end_idx": 1559, "document_id": "e7d2cc416005d62d2732e33b0c73c8a29b19e5689dd31c3635eca3d13a4d28d6", "doc_start_idx": 0, "answer_end_idx": 13, "answer_start_idx": 13, "document_position": 1 }, { "label": "grounded", "score": 0, "origin": "llm", "doc_end_idx": 1402, "document_id": "6ce80daeb86e789ebf57837a5bd539c60835bb3ad6c4fc8405f3365b382fbb61", "doc_start_idx": 0, "answer_end_idx": 18, "answer_start_idx": 18, "document_position": 2 }, { "label": "grounded", "score": 0, "origin": "llm", "doc_end_idx": 1576, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "doc_start_idx": 0, "answer_end_idx": 507, "answer_start_idx": 507, "document_position": 8 }, { "label": "grounded", "score": 0, "origin": "llm", "doc_end_idx": 1576, "document_id": "488b2156989f3b1745a7a9bbc8382833e7a94fa228b7d849c03a7b46832bb8e7", "doc_start_idx": 0, "answer_end_idx": 729, "answer_start_idx": 729, "document_position": 8 } ] }, "offsets_in_context": [], "prompt": "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nYou answer questions truthfully based on provided documents.\nFor each document check whether it is related to the question.\nOnly use documents that are related to the question to answer it.\nIgnore documents that are not related to the question.\nIf the answer exists in several documents, summarize them.\nOnly answer based on the documents provided. Don't make things up.\nIf the documents can't answer the question or you are unsure say: 'The answer can't be found in the text'.\nAlways use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3].\nNever name the documents, only enter a number in square brackets as a reference.\nThe reference must only refer to the number that comes in square brackets after the document.\nOtherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\nThese are the documents:\n\nDocument[1]:\nOverview\nMilk allergy is an atypical immune system response to milk and products containing milk. It's one of the most common food allergies in children. Cow's milk is the usual cause of milk allergy, but milk from sheep, goats, buffalo and other mammals also can cause a reaction.\nAn allergic reaction usually occurs soon after you or your child consumes milk. Signs and symptoms of milk allergy range from mild to severe and can include wheezing, vomiting, hives and digestive problems. Milk allergy can also cause anaphylaxis — a severe, life-threatening reaction.\nAvoiding milk and milk products is the primary treatment for milk allergy. Fortunately, most children outgrow milk allergy. Those who don't outgrow it may need to continue to avoid milk products.\nSymptoms\nMilk allergy symptoms, which differ from person to person, occur a few minutes to a few hours after you or your child drinks milk or eats milk products.\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\n\n\nDocument[2]:\nImmediate signs and symptoms of milk allergy might include:\nHives\nWheezing\nItching or tingling feeling around the lips or mouth\nSwelling of the lips, tongue or throat\nCoughing or shortness of breath\nVomiting\nSigns and symptoms that may take more time to develop include:\nLoose stools or diarrhea, which may contain blood\nAbdominal cramps\nRunny nose\nWatery eyes\nColic, in babies\nMilk allergy or milk intolerance?\nA true milk allergy differs from milk protein intolerance and lactose intolerance. Unlike milk allergy, intolerance doesn't involve the immune system. Milk intolerance requires different treatment from true milk allergy.\nCommon signs and symptoms of milk protein intolerance or lactose intolerance include digestive problems, such as bloating, gas or diarrhea, after consuming milk or products containing milk.\nAnaphylaxis\nMilk allergy can cause anaphylaxis, a life-threatening reaction that narrows the airways and can block breathing. Milk is the third most common food — after peanuts and tree nuts — to cause anaphylaxis.\nIf you or your child has a reaction to milk, tell your health care provider, no matter how mild the reaction. Tests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. \n\nDocument[3]:\nTests can help confirm milk allergy, so you can avoid future and potentially worse reactions.\nAnaphylaxis is a medical emergency and requires treatment with an epinephrine (adrenaline) shot (EpiPen, Adrenaclick, others) and a trip to the emergency room. Signs and symptoms start soon after milk consumption and can include:\nConstriction of airways, including a swollen throat that makes it difficult to breathe\nFacial flushing\nItching\nShock, with a marked drop in blood pressure\nWhen to see a doctor\nSee your provider or an allergist if you or your child experiences milk allergy symptoms shortly after consuming milk. If possible, see your provider during the allergic reaction to help make a diagnosis. Seek emergency treatment if you or your child develops signs or symptoms of anaphylaxis.\nCauses\nAll true food allergies are caused by an immune system malfunction. If you have milk allergy, your immune system identifies certain milk proteins as harmful, triggering the production of immunoglobulin E (IgE) antibodies to neutralize the protein (allergen). The next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\n\n\nDocument[4]:\nThe next time you come in contact with these proteins, immunoglobulin E (IgE) antibodies recognize them and signal your immune system to release histamine and other chemicals, causing a range of allergic signs and symptoms.\nThere are two main proteins in cow's milk that can cause an allergic reaction:\nCasein, found in the solid part (curd) of milk that curdles\nWhey, found in the liquid part of milk that remains after milk curdles\nYou or your child may be allergic to only one milk protein or to both. These proteins may be hard to avoid because they're also in some processed foods. And most people who react to cow's milk will react to sheep, goat and buffalo milk.\nFood protein-induced enterocolitis syndrome (FPIES)\nA food allergen can also cause what's sometimes called a delayed food allergy. Although any food can be a trigger, milk is one of the most common. The reaction, commonly vomiting and diarrhea, usually occurs within hours after eating the trigger rather than within minutes.\nUnlike some food allergies, food protein-induced enterocolitis syndrome (FPIES) usually resolves over time. As with milk allergy, preventing an FPIES reaction involves avoiding milk and milk products.\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. \n\nDocument[5]:\nRisk factors\nCertain factors may increase the risk of developing milk allergy:\nOther allergies. Many children who are allergic to milk also have other allergies. Milk allergy may develop before other allergies.\nAtopic dermatitis. Children who have atopic dermatitis — a common, chronic inflammation of the skin — are much more likely to develop a food allergy.\nFamily history. A person's risk of a food allergy increases if one or both parents have a food allergy or another type of allergy or allergic disease — such as hay fever, asthma, hives or eczema.\nAge. Milk allergy is more common in children. As they age, their digestive systems mature, and their bodies are less likely to react to milk.\nComplications\nChildren who are allergic to milk are more likely to develop certain other health problems, including:\nNutritional deficiencies. Because of dietary restrictions and feeding challenges, children with milk allergy may have slowed growth as well as vitamin and mineral deficiencies.\nReduced quality of life. Many common, and sometimes unexpected, foods contain milk, including some salad dressings or even hot dogs. If you or your child is severely allergic, avoiding milk exposure may increase stress or anxiety levels when it comes to making food choices.\nPrevention\nThere's no sure way to prevent a food allergy, but you can prevent reactions by avoiding the food that causes them. If you know you or your child is allergic to milk, avoid milk and milk products.\nRead food labels carefully. \n\nDocument[6]:\nSoy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. You may need to exclude from your diet all products that contain milk. Talk to your health care provider if you know — or suspect — that your child has milk allergy and develops allergy signs and symptoms after breastfeeding.\nIf you or your child is on a milk-free diet, your health care provider or dietitian can help you plan nutritionally balanced meals. You or your child may need to take supplements to replace calcium and nutrients found in milk, such as vitamin D and riboflavin.\n\nDocument[7]:\nDoes your steak have melted butter on it? Was your seafood dipped in milk before cooking?\nIf you're at risk of a serious allergic reaction, talk with your health care provider about carrying and using emergency epinephrine (adrenaline). If you have already had a severe reaction, wear a medical alert bracelet or necklace that lets others know you have a food allergy.\nMilk alternatives for infants\nIn children who are allergic to milk, breastfeeding and the use of hypoallergenic formula can prevent allergic reactions.\nBreastfeeding is the best source of nutrition for your infant. Breastfeeding for as long as possible is recommended, especially if your infant is at high risk of developing milk allergy.\nHypoallergenic formulas are produced by using enzymes to break down (hydrolyze) milk proteins, such as casein or whey. Further processing can include heat and filtering. Depending on their level of processing, products are classified as either partially or extensively hydrolyzed. Or they may also be called elemental formulas.\nSome hypoallergenic formulas aren't milk based, but instead contain amino acids. Besides extensively hydrolyzed products, amino-acid-based formulas are the least likely to cause an allergic reaction.\nSoy-based formulas are based on soy protein instead of milk. Soy formulas are fortified to be nutritionally complete — but, unfortunately, some children with a milk allergy also develop an allergy to soy.\nIf you're breastfeeding and your child is allergic to milk, cow's milk proteins passed through your breast milk may cause an allergic reaction. \n\nDocument[8]:\nThey may include:\nHives\nItchy, irritated skin\nNasal stuffiness (congestion)\nSwelling of the lips, face, tongue and throat, or other parts of the body\nWheezing or trouble breathing\nCoughing and choking or a tight feeling in the throat\nBelly (abdominal) pain, diarrhea, nausea or vomiting\nDizziness, lightheadedness or fainting\nAnaphylaxis\nAllergies can cause a severe, potentially life-threatening allergic reaction known as anaphylaxis. It can occur within seconds to minutes after exposure to something you're allergic to — and worsens quickly.\nAn anaphylactic reaction to shellfish is a medical emergency. Anaphylaxis requires immediate treatment with an epinephrine (adrenaline) injection and a follow-up trip to the emergency room. If anaphylaxis isn't treated right away, it can be fatal.\nAnaphylaxis causes the immune system to release a flood of chemicals that can cause you to go into shock. Signs and symptoms of anaphylaxis include:\nA swollen throat or tongue or a tightness in the throat (airway constriction) that makes it difficult for you to breathe\nCoughing, choking or wheezing with trouble breathing\nShock, with a severe drop in your blood pressure and a rapid or weak pulse\nSevere skin rash, hives, itching or swelling\nNausea, vomiting or diarrhea\nDizziness, lightheadedness or fainting\nWhen to see a doctor\nSeek emergency treatment if you develop signs or symptoms of anaphylaxis.\nSee a health care provider or allergy specialist if you have food allergy symptoms shortly after eating.\nCauses\nAll food allergies are caused by an immune system overreaction. \n\nQuestion: What are milk allergy symptomps? <|eot_id|><|start_header_id|>assistant<|end_header_id|>", "search": { "created_at": "2024-12-09T12:33:30.371439Z", "duration": 19.983364582061768, "query": "What are milk allergy symptomps?", "filters": {} } } } ```
### Delete Feedback You can delete feedback entries using the [Delete Feedback](/docs/api/main/delete-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-feedback-id-delete) endpoint. You need the following IDs to do this: - Workspace ID (check the workspace settings in ) - Pipeline ID (check the Pipeline Details page in ) - Feedback ID (from the [Create Feedback](/docs/api/main/create-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-post) or [Get Paginated Feedback](/docs/api/main/get-paginated-feedback-api-v-2-workspaces-workspace-id-pipelines-pipeline-id-feedback-get) endpoints) You can use this code to construct your request. Make sure you update the variables: the IDs and the API key: ```python url = "https://api.cloud.deepset.ai/api/v2/workspaces//pipelines//feedback/" headers = { "accept": "application/json", "authorization": "Bearer " } response = requests.delete(url, headers=headers) print(response) ``` ```curl curl --request DELETE \ --url https://api.cloud.deepset.ai/api/v2/workspaces//pipelines//feedback/ \ --header 'accept: application/json' \ --header 'authorization: Bearer ' ``` # Example Colab Notebook Use this Colab Notebook [![Feedback API Notebook](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/130ACcEGY0fEAuaAshZY0REclmkC2Zmmn#scrollTo=c84070bb-8a2e-47a2-a916-7c0a53ccf63e) to see how working with feedback through REST API works in practice. In the notebook, you: - run a search on a pipeline. - obtain all the necessary IDs. - add, update, and delete feedback entries. --- ## Tutorial: Creating a Chat App Through REST API # Tutorial: Creating a Chat App With REST API Create a chat app that can answer questions about Python Enhancement Proposals (PEPs) using REST API endpoints. *** - **Level**: Basic - **Time to complete**: 15 minutes - **Prerequisites**: - You must have a basic understanding of REST API: HTTP methods, response and request structure, and basic concepts. - Basic programming knowledge is a plus. - You must have a API key. For instructions, see [Generate an API Key](/docs/how-to-guides/managing-access/generate-api-key.mdx). - OpenAI API key to use GPT models. (This tutorial uses GPT-4, but you can exchange it for another model.) - **Goal**: After completing this tutorial, you will have built a chat assistant that runs on Python Enhancements Proposals and can answer questions about the contents of the https://peps.python.org/ website. You'll be able to plug it into a UI of your choice. *** ## Upload Files First, let's upload the files our chat will run on. 1. Download the peps_main.zip file to your machine and unzip it. 2. Create a new workspace: 1. Log in to and click the workspace name to expand the workspace list. 2. Type `peps` as the new workspace name and click **Create**. You're automatically moved to the new workspace. 3. In the navigation, click _Files>Upload Files_. 4. Choose the files you extracted in step 1 and click **Upload**. You should have 664 files. **Result**: You have uploaded 664 files containing to your workspace. ## Create a Chat Pipeline Now, we'll create a chat pipeline you'll later call with REST API endpoints. 1. In , ensure you're in the same workspace where you uploaded the files, and click **Pipeline Templates**. 2. Choose _Conversational_ templates, hover over _RAG Chat_, and click **Use Template**. 3. Rename the pipeline to `rag-chat` and click **Create Pipeline**. The pipeline opens in Pipeline Builder. 4. Find `OpenSearchDocumentStore` among your pipeline components and click it to open the configuration. You'll notice it shows a warning that an index is missing. Choose the `Standard-Index_English` index on the component card. 5. Save and deploy the pipeline. **Result**: You have created and deployed a chat pipeline. It's ready for use. ## Call the Pipeline with REST API To send user queries to your chat pipelines: 1. Get the ID of your chat pipeline. You can do this in the UI by clicking the pipeline name and checking the ID on the Pipeline Details page. 2. Create a search session with the [Create Search Session](/docs/api/main/create-search-session-api-v-1-workspaces-workspace-name-search-sessions-post) endpoint. 3. Send user queries using the [Chat](/docs/api/main/chat-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-post) endpoint. ### Create a Search Session Search session lets you display chat history when running queries. Use the [Create Search Session](/docs/api/main/create-search-session-api-v-1-workspaces-workspace-name-search-sessions-post) endpoint. You'll need to provide the following information: - your workspace name (in the URL). - your chat pipeline ID (you can find it in the Get Pipeline response). - your API key (in headers). Here is a sample code you can use: ```python url = "https://api.cloud.deepset.ai/api/v1/workspaces/peps/search_sessions" #legal-chat is the workspace name payload = { "pipeline_id": "" } #insert the pipeline ID you got in the Get Pipeline response headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer " #insert your deepset API key } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/peps/search_sessions \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data ' { "pipeline_id": "" } ' ``` As a response, you get the search session ID, which you'll need to start the chat: ```json { "search_session_id": "52bda5ec-23d9-4240-9d12-e7c48513158b" } ``` ### Start a Chat Send your queries to the [Chat](/docs/api/main/chat-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-post) endpoint to start chatting with your pipeline. You'll need to provide: - your pipeline and workspace name (in the URL). - your API key (in headers). - queries - search session ID (from the Create Search Session response) You can use this code snippet: ```python url = "https://api.cloud.deepset.ai/api/v1/workspaces/peps/pipelines/rag-chat/chat" #peps is the workspace name, rag-chat is the pipeline name payload = { "chat_history_limit": 3, # the number of chat history items to show in the chat "debug": False, "view_prompts": False, "queries": ["How do you present datetime objects in human readable format?"], # the queries to ask "search_session_id": "52bda5ec-23d9-4240-9d12-e7c48513158b" # ID of the search session } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer " # your deepset API key } response = requests.post(url, json=payload, headers=headers) print(response.text) ``` ```curl curl --request POST \ --url https://api.cloud.deepset.ai/api/v1/workspaces/peps/pipelines/rag-chat/chat \ --header 'accept: application/json' \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --data ' { "chat_history_limit": 3, "debug": false, "view_prompts": false, "queries": [ "How do you present datetime objects in human readable format?" ], "search_session_id": "52bda5ec-23d9-4240-9d12-e7c48513158b" } ' ```
Sample response ```json { "query_id": "036b2866-2703-4d59-823d-9d8e683c7fa1", "results": [ { "query_id": "036b2866-2703-4d59-823d-9d8e683c7fa1", "query": "How do you present datetime objects in human readable format?", "answers": [ { "answer": "To present datetime objects in a human-readable format, you can use the `strftime()` method provided by the `datetime` class. This method allows you to specify the format of the output string using format specifiers that correspond to various components of the date and time. For example, you can format a datetime object to display the date and time in a readable format like \"Today is: {0:%a %b %d %H:%M:%S %Y}\". This would output a string such as \"Today is: Mon Sep 16 10:34:54 2023\" . Additionally, the `isoformat()` and `ctime()` methods on datetime objects return string representations of the time in ISO 8601 format and a more traditional format similar to the C function `asctime()`, respectively .", "type": "generative", "score": null, "context": null, "offsets_in_document": [], "offsets_in_context": [], "document_id": null, "document_ids": [ "7001548c9e254ad0d2a35c1fea7a93ebaca5edc7f7e58ccbdf9bb2c665960040", "b4f79b5862793f5fa1c3f9b669a1c27e1a9aa9cff9b6481fa0de2513b3c3264d", "edbc2088c4f9922d1e38554a6e1919508f3d739682abb07769ff14bcfd53c132", "a83b9c8fdf043d00e92fe0247e5913ea5de8234b6c5a793efbafd410f01e418b", "bdf4d62f2f52e9a3d1e87e6e41b9679ada4a930c321d33d3e77544c137cb88fb", "d707bfed2ede5435c51068efc5690033457d7e3106572b2221ee30097e16c20e", "66722fd08f8adab75357847e2d8ab324d6175816435c99063e2c2d8a96171d74", "d9878e926481ac189a88db4f7ed36cb64cd9e28bd58c450ee11c2731dba935d6" ], "meta": { "_references": [ { "answer_end_idx": 487, "answer_start_idx": 487, "document_id": "edbc2088c4f9922d1e38554a6e1919508f3d739682abb07769ff14bcfd53c132", "document_position": 3, "label": "grounded", "score": 0, "doc_end_idx": 1607, "doc_start_idx": 0, "origin": "llm" }, { "answer_end_idx": 706, "answer_start_idx": 706, "document_id": "7001548c9e254ad0d2a35c1fea7a93ebaca5edc7f7e58ccbdf9bb2c665960040", "document_position": 1, "label": "grounded", "score": 0, "doc_end_idx": 1738, "doc_start_idx": 0, "origin": "llm" } ] }, "file": { "id": "3ee143f6-47b8-4ceb-bd69-0b0eede32aac", "name": "pep-0321.txt" }, "files": [ { "id": "3ee143f6-47b8-4ceb-bd69-0b0eede32aac", "name": "pep-0321.txt" }, { "id": "c549dad4-9306-417e-9e31-72eff4db300c", "name": "pep-0498.txt" }, { "id": "d6987234-60e7-4651-864d-017631ca53b3", "name": "pep-3101.txt" }, { "id": "25a9a573-222b-4fc4-b284-a776903ed1ea", "name": "pep-0495.txt" }, { "id": "5eda3f1a-74b9-4887-9772-35ca44be1e99", "name": "pep-0410.txt" }, { "id": "cf52312b-26b9-4ded-ac2b-cb6faf344a86", "name": "pep-0500.txt" }, { "id": "a8a8d83e-6696-46c7-9ebf-3a953da41132", "name": "pep-0519.txt" } ], "result_id": "7ec72d79-639a-4291-8258-86a173ec02ae", "prompt": "You are a technical expert.\nYou answer questions truthfully based on provided documents.\nIf the answer exists in several documents, summarize them.\nIgnore documents that don't contain the answer to the question.\nOnly answer based on the documents provided. Don't make things up.\nIf no information related to the question can be found in the document, say so.\nAlways use references in the form [NUMBER OF DOCUMENT] when using information from a document, e.g. [3] for Document[3].\nNever name the documents, only enter a number in square brackets as a reference.\nThe reference must only refer to the number that comes in square brackets after the document.\nOtherwise, do not use brackets in your answer and reference ONLY the number of the document without mentioning the word document.\nThese are the documents:\n\nDocument[1]:\nPEP: 321\nTitle: Date/Time Parsing and Formatting\nVersion: $Revision$\nLast-Modified: $Date$\nAuthor: A.M. Kuchling \nStatus: Withdrawn\nType: Standards Track\nContent-Type: text/x-rst\nCreated: 16-Sep-2003\nPython-Version: 2.4\nPost-History:\n\n\nAbstract\n========\n\nPython 2.3 added a number of simple date and time types in the\n``datetime`` module. There's no support for parsing strings in various\nformats and returning a corresponding instance of one of the types.\nThis PEP proposes adding a family of predefined parsing function for\nseveral commonly used date and time formats, and a facility for generic\nparsing.\n\nThe types provided by the ``datetime`` module all have\n``.isoformat()`` and ``.ctime()`` methods that return string\nrepresentations of a time, and the ``.strftime()`` method can be used\nto construct new formats. There are a number of additional\ncommonly-used formats that would be useful to have as part of the\nstandard library; this PEP also suggests how to add them.\n\n\nInput Formats\n=======================\n\nUseful formats to support include:\n\n* `ISO8601`_\n* ARPA/:rfc:`2822`\n* `ctime`_\n* Formats commonly written by humans such as the American\n \"MM/DD/YYYY\", the European \"YYYY/MM/DD\", and variants such as\n \"DD-Month-YYYY\".\n* CVS-style or tar-style dates (\"tomorrow\", \"12 hours ago\", etc.)\n\nXXX The Perl `ParseDate.pm`_ module supports many different input formats,\nboth absolute and relative. Should we try to support them all?\n\nOptions:\n\n1) Add functions to the ``datetime`` module::\n\n import datetime\n d = datetime.parse_iso8601(\"2003-09-15T10:34:54\")\n\n2) Add class methods to the various types. There are already various\n class methods such as ``.now()``, so this would be pretty natural.\n\nDocument[2]:\nHowever, ``str.format()`` is not without its issues. Chief among them\nis its verbosity. For example, the text ``value`` is repeated here::\n\n >>> value = 4 * 20\n >>> 'The value is {value}.'.format(value=value)\n 'The value is 80.'Even in its simplest form there is a bit of boilerplate, and the value\nthat's inserted into the placeholder is sometimes far removed from\nwhere the placeholder is situated::\n\n >>> 'The value is {}.'.format(value)\n 'The value is 80.'With an f-string, this becomes::\n\n >>> f'The value is {value}.''The value is 80.'F-strings provide a concise, readable way to include the value of\nPython expressions inside strings.\n\nIn this sense, ``string.Template`` and %-formatting have similar\nshortcomings to ``str.format()``, but also support fewer formatting\noptions. In particular, they do not support the ``__format__``\nprotocol, so that there is no way to control how a specific object is\nconverted to a string, nor can it be extended to additional types that\nwant to control how they are converted to strings (such as ``Decimal``\nand ``datetime``). This example is not possible with\n``string.Template``::\n\n >>> value = 1234\n >>> f'input={value:#06x}'\n 'input=0x04d2'\n\nAnd neither %-formatting nor ``string.Template`` can control\nformatting such as::\n\n >>> date = datetime.date(1991, 10, 12)\n >>> f'{date} was on a {date:%A}'\n '1991-10-12 was on a Saturday'\n\nNo use of globals() or locals()\n-------------------------------\n\nIn the discussions on python-dev [#]_, a number of solutions where\npresented that used locals() and globals() or their equivalents. All\nof these have various problems. \n\nDocument[3]:\nSame as 'g' except switches to 'E'\n if the number gets to large.\n 'n' - Number. This is the same as 'g', except that it uses the\n current locale setting to insert the appropriate\n number separator characters.\n '%' - Percentage. Multiplies the number by 100 and displays\n in fixed ('f') format, followed by a percent sign.\n '' (None) - similar to 'g', except that it prints at least one\n digit after the decimal point.\n\nObjects are able to define their own format specifiers to\nreplace the standard ones. An example is the 'datetime' class,\nwhose format specifiers might look something like the\narguments to the ``strftime()`` function::\n\n \"Today is: {0:%a %b %d %H:%M:%S %Y}\".format(datetime.now())\n\nFor all built-in types, an empty format specification will produce\nthe equivalent of ``str(value)``. It is recommended that objects\ndefining their own format specifiers follow this convention as\nwell.\n\n\nExplicit Conversion Flag\n------------------------\n\nThe explicit conversion flag is used to transform the format field value\nbefore it is formatted. This can be used to override the type-specific\nformatting behavior, and format the value as if it were a more\ngeneric type. Currently, two explicit conversion flags are\nrecognized::\n\n !r - convert the value to a string using repr().\n !s - convert the value to a string using str().\n\nThese flags are placed before the format specifier::\n\n \"{0!r:20}\".format(\"Hello\")\n\nIn the preceding example, the string \"Hello\" will be printed, with quotes,\nin a field of at least 20 characters width.\n\n\n\nDocument[4]:\nOnly complicated formats need to be supported; :rfc:`2822`\nis currently the only one I can think of.\n\nOptions:\n\n1) Provide predefined format strings, so you could write this::\n\n import datetime\n d = datetime.datetime(...)\n print d.strftime(d.RFC2822_FORMAT) # or datetime.RFC2822_FORMAT?\n\n2) Provide new methods on all the objects::\n\n d = datetime.datetime(...)\n print d.rfc822_time()\n\n\nRelevant functionality in other languages includes the `PHP date`_\nfunction (Python implementation by Simon Willison at\nhttp://simon.incutio.com/archive/2003/10/07/dateInPython)\n\n\nReferences\n==========\n\n.. _ISO8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html\n\n.. _ParseDate.pm: http://search.cpan.org/author/MUIR/Time-modules-2003.0211/lib/Time/ParseDate.pm\n\n.. _ctime: http://www.opengroup.org/onlinepubs/007908799/xsh/asctime.html\n\n.. _PHP date: http://www.php.net/date\n\nOther useful links:\n\nhttp://www.egenix.com/files/python/mxDateTime.html\nhttp://ringmaster.arc.nasa.gov/tools/time_formats.html\nhttp://www.thinkage.ca/english/gcos/expl/b/lib/0tosec.html\nhttps://moin.conectiva.com.br/DateUtil\n\n\nCopyright\n=========\n\nThis document has been placed in the public domain.\n\n\n\f\n..\n Local Variables:\n mode: indented-text\n indent-tabs-mode: nil\n sentence-end-double-space: t\n fill-column: 70\n End:\n\nDocument[5]:\nOnly datetime/time instances with ``fold=1`` pickled\nin the new versions will become unreadable by the older Python\nversions. Pickles of instances with ``fold=0`` (which is the\ndefault) will remain unchanged.\n\n\nQuestions and Answers\n=====================\n\nWhy not call the new flag \"isdst\"?\n----------------------------------\n\nA non-technical answer\n......................\n\n* Alice: Bob - let's have a stargazing party at 01:30 AM tomorrow!\n* Bob: Should I presume initially that Daylight Saving Time is or is\n not in effect for the specified time?\n* Alice: Huh?\n\n-------\n\n* Bob: Alice - let's have a stargazing party at 01:30 AM tomorrow!\n* Alice: You know, Bob, 01:30 AM will happen twice tomorrow. Which time do you have in mind?\n* Bob: I did not think about it, but let's pick the first.\n\n-------\n\n(same characters, an hour later)\n\n-------\n\n* Bob: Alice - this Py-O-Clock gadget of mine asks me to choose\n between fold=0 and fold=1 when I set it for tomorrow 01:30 AM.\n What should I do?\n* Alice: I've never hear of a Py-O-Clock, but I guess fold=0 is\n the first 01:30 AM and fold=1 is the second.\n\n\nA technical reason\n..................\n\nWhile the ``tm_isdst`` field of the ``time.struct_time`` object can be\nused to disambiguate local times in the fold, the semantics of such\ndisambiguation are completely different from the proposal in this PEP.\n\n\n\nDocument[6]:\nThere is also an ordering issues with daylight saving time (DST) in\nthe duplicate hour of switching from DST to normal time.\n\ndatetime.datetime has been rejected because it cannot be used for functions\nusing an unspecified starting point like os.times() or time.clock().\n\nFor time.time() and time.clock_gettime(time.CLOCK_GETTIME): it is already\npossible to get the current time as a datetime.datetime object using::\n\n datetime.datetime.now(datetime.timezone.utc)\n\nFor os.stat(), it is simple to create a datetime.datetime object from a\ndecimal.Decimal timestamp in the UTC timezone::\n\n datetime.datetime.fromtimestamp(value, datetime.timezone.utc)\n\n.. note::\n datetime.datetime only supports microsecond resolution, but can be enhanced\n to support nanosecond.\n\ndatetime.timedelta\n------------------\n\ndatetime.timedelta is the natural choice for a relative timestamp because it is\nclear that this type contains a timestamp, whereas int, float and Decimal are\nraw numbers. It can be used with datetime.datetime to get an absolute timestamp\nwhen the starting point is known.\n\ndatetime.timedelta has been rejected because it cannot be coerced to float and\nhas a fixed resolution. One new standard timestamp type is enough, Decimal is\npreferred over datetime.timedelta. Converting a datetime.timedelta to float\nrequires an explicit call to the datetime.timedelta.total_seconds() method.\n\n.. note::\n datetime.timedelta only supports microsecond resolution, but can be enhanced\n to support nanosecond.\n\n\n.. _tuple:\n\nTuple of integers\n-----------------\n\nTo expose C functions in Python, a tuple of integers is the natural choice to\nstore a timestamp because the C language uses structures with integers fields\n(e.g. timeval and timespec structures). Using only integers avoids the loss of\nprecision (Python supports integers of arbitrary length). \n\nDocument[7]:\nPEP: 500\nTitle: A protocol for delegating datetime methods to their tzinfo implementations\nVersion: $Revision$\nLast-Modified: $Date$\nAuthor: Alexander Belopolsky , Tim Peters \nDiscussions-To: datetime-sig@python.org\nStatus: Rejected\nType: Standards Track\nContent-Type: text/x-rst\nRequires: 495\nCreated: 08-Aug-2015\nResolution: https://mail.python.org/pipermail/datetime-sig/2015-August/000354.html\n\nAbstract\n========\n\nThis PEP specifies a new protocol (PDDM - \"A Protocol for Delegating\nDatetime Methods\") that can be used by concrete implementations of the\n``datetime.tzinfo`` interface to override aware datetime arithmetics,\nformatting and parsing. We describe changes to the\n``datetime.datetime`` class to support the new protocol and propose a\nnew abstract class ``datetime.tzstrict`` that implements parts of this\nprotocol necessary to make aware datetime instances to follow \"strict\"\narithmetic rules.\n\n\nRationale\n=========\n\nAs of Python 3.5, aware datetime instances that share a ``tzinfo``\nobject follow the rules of arithmetics that are induced by a simple\nbijection between (year, month, day, hour, minute, second,\nmicrosecond) 7-tuples and large integers. In this arithmetics, the\ndifference between YEAR-11-02T12:00 and YEAR-11-01T12:00 is always 24\nhours, even though in the US/Eastern timezone, for example, there are\n25 hours between 2014-11-01T12:00 and 2014-11-02T12:00 because the\nlocal clocks were rolled back one hour at 2014-11-02T02:00,\nintroducing an extra hour in the night between 2014-11-01 and\n2014-11-02.\n\nMany business applications require the use of Python's simplified view\nof local dates. No self-respecting car rental company will charge its\ncustomers more for a week that straddles the end of DST than for any\nother week or require that they return the car an hour early.\n\n\nDocument[8]:\nOne part is the proposal of a\nprotocol for objects to declare and provide support for exposing a\nfile system path representation. The other part deals with changes to\nPython's standard library to support the new protocol. These changes\nwill also lead to the pathlib module dropping its provisional status.\n\nProtocol\n--------\n\nThe following abstract base class defines the protocol for an object\nto be considered a path object::\n\n import abc\n import typing as t\n\n\n class PathLike(abc.ABC):\n\n \"\"\"Abstract base class for implementing the file system path protocol.\"\"\"@abc.abstractmethod\n def __fspath__(self) -> t.Union[str, bytes]:\n \"\"\"Return the file system path representation of the object.\"\"\"raise NotImplementedError\n\n\nObjects representing file system paths will implement the\n``__fspath__()`` method which will return the ``str`` or ``bytes``\nrepresentation of the path. The ``str`` representation is the\npreferred low-level path representation as it is human-readable and\nwhat people historically represent paths as.\n\n\nStandard library changes\n------------------------\n\nIt is expected that most APIs in Python's standard library that\ncurrently accept a file system path will be updated appropriately to\naccept path objects (whether that requires code or simply an update\nto documentation will vary). The modules mentioned below, though,\ndeserve specific details as they have either fundamental changes that\nempower the ability to use path objects, or entail additions/removal\nof APIs.\n\n\nbuiltins\n''''''''\n\n``open()`` [#builtins-open]_ will be updated to accept path objects as\nwell as continue to accept ``str`` and ``bytes``.\n\n\n\n\nQuestion: How do you present datetime objects in human readable format?\nAnswer:" } ], "documents": [ { "id": "7001548c9e254ad0d2a35c1fea7a93ebaca5edc7f7e58ccbdf9bb2c665960040", "content": "PEP: 321\nTitle: Date/Time Parsing and Formatting\nVersion: $Revision$\nLast-Modified: $Date$\nAuthor: A.M. Kuchling \nStatus: Withdrawn\nType: Standards Track\nContent-Type: text/x-rst\nCreated: 16-Sep-2003\nPython-Version: 2.4\nPost-History:\n\n\nAbstract\n========\n\nPython 2.3 added a number of simple date and time types in the\n``datetime`` module. There's no support for parsing strings in various\nformats and returning a corresponding instance of one of the types.\nThis PEP proposes adding a family of predefined parsing function for\nseveral commonly used date and time formats, and a facility for generic\nparsing.\n\nThe types provided by the ``datetime`` module all have\n``.isoformat()`` and ``.ctime()`` methods that return string\nrepresentations of a time, and the ``.strftime()`` method can be used\nto construct new formats. There are a number of additional\ncommonly-used formats that would be useful to have as part of the\nstandard library; this PEP also suggests how to add them.\n\n\nInput Formats\n=======================\n\nUseful formats to support include:\n\n* `ISO8601`_\n* ARPA/:rfc:`2822`\n* `ctime`_\n* Formats commonly written by humans such as the American\n \"MM/DD/YYYY\", the European \"YYYY/MM/DD\", and variants such as\n \"DD-Month-YYYY\".\n* CVS-style or tar-style dates (\"tomorrow\", \"12 hours ago\", etc.)\n\nXXX The Perl `ParseDate.pm`_ module supports many different input formats,\nboth absolute and relative. Should we try to support them all?\n\nOptions:\n\n1) Add functions to the ``datetime`` module::\n\n import datetime\n d = datetime.parse_iso8601(\"2003-09-15T10:34:54\")\n\n2) Add class methods to the various types. There are already various\n class methods such as ``.now()``, so this would be pretty natural.", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 0, 279 ], "doc_id": "850d4b3a9055c249407bc6c2577ffd340ffb1e297f532513274d584b899f42c0" } ], "split_idx_start": 0, "file_name": "pep-0321.txt", "_file_created_at": "2024-10-18T09:04:08.908838+00:00", "split_id": 0, "_file_size": 4372, "page_number": 1, "source_id": "0f5123e030c45b644e8c5db6c65c4beadbf11c82bf30e48a99f7b9ed02c696e9" }, "score": 0.09124755859375, "embedding": null, "file": { "id": "3ee143f6-47b8-4ceb-bd69-0b0eede32aac", "name": "pep-0321.txt" }, "result_id": "f93ab9cc-76ec-4120-9cfe-e6ac374b6684" }, { "id": "b4f79b5862793f5fa1c3f9b669a1c27e1a9aa9cff9b6481fa0de2513b3c3264d", "content": "However, ``str.format()`` is not without its issues. Chief among them\nis its verbosity. For example, the text ``value`` is repeated here::\n\n >>> value = 4 * 20\n >>> 'The value is {value}.'.format(value=value)\n 'The value is 80.'Even in its simplest form there is a bit of boilerplate, and the value\nthat's inserted into the placeholder is sometimes far removed from\nwhere the placeholder is situated::\n\n >>> 'The value is {}.'.format(value)\n 'The value is 80.'With an f-string, this becomes::\n\n >>> f'The value is {value}.''The value is 80.'F-strings provide a concise, readable way to include the value of\nPython expressions inside strings.\n\nIn this sense, ``string.Template`` and %-formatting have similar\nshortcomings to ``str.format()``, but also support fewer formatting\noptions. In particular, they do not support the ``__format__``\nprotocol, so that there is no way to control how a specific object is\nconverted to a string, nor can it be extended to additional types that\nwant to control how they are converted to strings (such as ``Decimal``\nand ``datetime``). This example is not possible with\n``string.Template``::\n\n >>> value = 1234\n >>> f'input={value:#06x}'\n 'input=0x04d2'\n\nAnd neither %-formatting nor ``string.Template`` can control\nformatting such as::\n\n >>> date = datetime.date(1991, 10, 12)\n >>> f'{date} was on a {date:%A}'\n '1991-10-12 was on a Saturday'\n\nNo use of globals() or locals()\n-------------------------------\n\nIn the discussions on python-dev [#]_, a number of solutions where\npresented that used locals() and globals() or their equivalents. All\nof these have various problems. ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1194, 1425 ], "doc_id": "d873a90f56222b0c02ef2987a6ef2390aa5f7400bb6f8fe5c1cfafebaba3a9d4" }, { "range": [ 0, 548 ], "doc_id": "76db0307a81ca4d9012184b0066414935f4342f14219f177170a61737d6bfd2c" } ], "split_idx_start": 3396, "file_name": "pep-0498.txt", "_file_created_at": "2024-10-18T09:03:54.839485+00:00", "split_id": 3, "_file_size": 25320, "page_number": 1, "source_id": "51927b0152d7c0504de7a4e0a4f5265617143fce6a5f763d17118f6afdc92298" }, "score": 0.06280517578125, "embedding": null, "file": { "id": "c549dad4-9306-417e-9e31-72eff4db300c", "name": "pep-0498.txt" }, "result_id": "0c46d7af-4542-4b1e-ac23-95d5d2bdbc7c" }, { "id": "edbc2088c4f9922d1e38554a6e1919508f3d739682abb07769ff14bcfd53c132", "content": "Same as 'g' except switches to 'E'\n if the number gets to large.\n 'n' - Number. This is the same as 'g', except that it uses the\n current locale setting to insert the appropriate\n number separator characters.\n '%' - Percentage. Multiplies the number by 100 and displays\n in fixed ('f') format, followed by a percent sign.\n '' (None) - similar to 'g', except that it prints at least one\n digit after the decimal point.\n\nObjects are able to define their own format specifiers to\nreplace the standard ones. An example is the 'datetime' class,\nwhose format specifiers might look something like the\narguments to the ``strftime()`` function::\n\n \"Today is: {0:%a %b %d %H:%M:%S %Y}\".format(datetime.now())\n\nFor all built-in types, an empty format specification will produce\nthe equivalent of ``str(value)``. It is recommended that objects\ndefining their own format specifiers follow this convention as\nwell.\n\n\nExplicit Conversion Flag\n------------------------\n\nThe explicit conversion flag is used to transform the format field value\nbefore it is formatted. This can be used to override the type-specific\nformatting behavior, and format the value as if it were a more\ngeneric type. Currently, two explicit conversion flags are\nrecognized::\n\n !r - convert the value to a string using repr().\n !s - convert the value to a string using str().\n\nThese flags are placed before the format specifier::\n\n \"{0!r:20}\".format(\"Hello\")\n\nIn the preceding example, the string \"Hello\" will be printed, with quotes,\nin a field of at least 20 characters width.\n\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1386, 1647 ], "doc_id": "0080ddf63825baab764048b3e068878bd23701f44610365cd5808be57d4fe36d" }, { "range": [ 0, 255 ], "doc_id": "2629b8672811bd4a8a6da1adaa55dc166d2fc0e3ba1b8336690e7599c77cc5f2" } ], "split_idx_start": 12752, "file_name": "pep-3101.txt", "_file_created_at": "2024-10-18T09:03:29.826858+00:00", "split_id": 11, "_file_size": 33149, "page_number": 1, "source_id": "b42e3a8de46bd3686eb4e0ec3015b34e916f424f29e9398acb58d062e89c15bf" }, "score": 0.05792236328125, "embedding": null, "file": { "id": "d6987234-60e7-4651-864d-017631ca53b3", "name": "pep-3101.txt" }, "result_id": "e497e02b-3aa9-498c-b687-fc850ed4398f" }, { "id": "a83b9c8fdf043d00e92fe0247e5913ea5de8234b6c5a793efbafd410f01e418b", "content": "Only complicated formats need to be supported; :rfc:`2822`\nis currently the only one I can think of.\n\nOptions:\n\n1) Provide predefined format strings, so you could write this::\n\n import datetime\n d = datetime.datetime(...)\n print d.strftime(d.RFC2822_FORMAT) # or datetime.RFC2822_FORMAT?\n\n2) Provide new methods on all the objects::\n\n d = datetime.datetime(...)\n print d.rfc822_time()\n\n\nRelevant functionality in other languages includes the `PHP date`_\nfunction (Python implementation by Simon Willison at\nhttp://simon.incutio.com/archive/2003/10/07/dateInPython)\n\n\nReferences\n==========\n\n.. _ISO8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html\n\n.. _ParseDate.pm: http://search.cpan.org/author/MUIR/Time-modules-2003.0211/lib/Time/ParseDate.pm\n\n.. _ctime: http://www.opengroup.org/onlinepubs/007908799/xsh/asctime.html\n\n.. _PHP date: http://www.php.net/date\n\nOther useful links:\n\nhttp://www.egenix.com/files/python/mxDateTime.html\nhttp://ringmaster.arc.nasa.gov/tools/time_formats.html\nhttp://www.thinkage.ca/english/gcos/expl/b/lib/0tosec.html\nhttps://moin.conectiva.com.br/DateUtil\n\n\nCopyright\n=========\n\nThis document has been placed in the public domain.\n\n\n\f\n..\n Local Variables:\n mode: indented-text\n indent-tabs-mode: nil\n sentence-end-double-space: t\n fill-column: 70\n End:", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1582, 1892 ], "doc_id": "850d4b3a9055c249407bc6c2577ffd340ffb1e297f532513274d584b899f42c0" } ], "split_idx_start": 3041, "file_name": "pep-0321.txt", "_file_created_at": "2024-10-18T09:04:08.908838+00:00", "split_id": 2, "_file_size": 4372, "page_number": 1, "source_id": "0f5123e030c45b644e8c5db6c65c4beadbf11c82bf30e48a99f7b9ed02c696e9" }, "score": 0.02606201171875, "embedding": null, "file": { "id": "3ee143f6-47b8-4ceb-bd69-0b0eede32aac", "name": "pep-0321.txt" }, "result_id": "0956c775-a701-40e9-b914-5fdf82c42f19" }, { "id": "bdf4d62f2f52e9a3d1e87e6e41b9679ada4a930c321d33d3e77544c137cb88fb", "content": "Only datetime/time instances with ``fold=1`` pickled\nin the new versions will become unreadable by the older Python\nversions. Pickles of instances with ``fold=0`` (which is the\ndefault) will remain unchanged.\n\n\nQuestions and Answers\n=====================\n\nWhy not call the new flag \"isdst\"?\n----------------------------------\n\nA non-technical answer\n......................\n\n* Alice: Bob - let's have a stargazing party at 01:30 AM tomorrow!\n* Bob: Should I presume initially that Daylight Saving Time is or is\n not in effect for the specified time?\n* Alice: Huh?\n\n-------\n\n* Bob: Alice - let's have a stargazing party at 01:30 AM tomorrow!\n* Alice: You know, Bob, 01:30 AM will happen twice tomorrow. Which time do you have in mind?\n* Bob: I did not think about it, but let's pick the first.\n\n-------\n\n(same characters, an hour later)\n\n-------\n\n* Bob: Alice - this Py-O-Clock gadget of mine asks me to choose\n between fold=0 and fold=1 when I set it for tomorrow 01:30 AM.\n What should I do?\n* Alice: I've never hear of a Py-O-Clock, but I guess fold=0 is\n the first 01:30 AM and fold=1 is the second.\n\n\nA technical reason\n..................\n\nWhile the ``tm_isdst`` field of the ``time.struct_time`` object can be\nused to disambiguate local times in the fold, the semantics of such\ndisambiguation are completely different from the proposal in this PEP.\n\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1389, 1681 ], "doc_id": "a1270e82b4dbf104c429342bb71fb0a7fc80db41719f0d2a79ffa88215e9ced6" }, { "range": [ 0, 211 ], "doc_id": "ea7d03dac129035cacbb28d07304048f31e99487736aecb2df16b8903874ccca" } ], "split_idx_start": 23551, "file_name": "pep-0495.txt", "_file_created_at": "2024-10-18T09:03:54.819307+00:00", "split_id": 18, "_file_size": 34899, "page_number": 1, "source_id": "04ae5810b522e53d51d5bb1f7e708f045a1e09977cde5b7e18a54646ffa0575f" }, "score": 0.020294189453125, "embedding": null, "file": { "id": "25a9a573-222b-4fc4-b284-a776903ed1ea", "name": "pep-0495.txt" }, "result_id": "77aed3e6-8840-4edf-a532-e9b66375b1e2" }, { "id": "d707bfed2ede5435c51068efc5690033457d7e3106572b2221ee30097e16c20e", "content": "There is also an ordering issues with daylight saving time (DST) in\nthe duplicate hour of switching from DST to normal time.\n\ndatetime.datetime has been rejected because it cannot be used for functions\nusing an unspecified starting point like os.times() or time.clock().\n\nFor time.time() and time.clock_gettime(time.CLOCK_GETTIME): it is already\npossible to get the current time as a datetime.datetime object using::\n\n datetime.datetime.now(datetime.timezone.utc)\n\nFor os.stat(), it is simple to create a datetime.datetime object from a\ndecimal.Decimal timestamp in the UTC timezone::\n\n datetime.datetime.fromtimestamp(value, datetime.timezone.utc)\n\n.. note::\n datetime.datetime only supports microsecond resolution, but can be enhanced\n to support nanosecond.\n\ndatetime.timedelta\n------------------\n\ndatetime.timedelta is the natural choice for a relative timestamp because it is\nclear that this type contains a timestamp, whereas int, float and Decimal are\nraw numbers. It can be used with datetime.datetime to get an absolute timestamp\nwhen the starting point is known.\n\ndatetime.timedelta has been rejected because it cannot be coerced to float and\nhas a fixed resolution. One new standard timestamp type is enough, Decimal is\npreferred over datetime.timedelta. Converting a datetime.timedelta to float\nrequires an explicit call to the datetime.timedelta.total_seconds() method.\n\n.. note::\n datetime.timedelta only supports microsecond resolution, but can be enhanced\n to support nanosecond.\n\n\n.. _tuple:\n\nTuple of integers\n-----------------\n\nTo expose C functions in Python, a tuple of integers is the natural choice to\nstore a timestamp because the C language uses structures with integers fields\n(e.g. timeval and timespec structures). Using only integers avoids the loss of\nprecision (Python supports integers of arbitrary length). ", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1272, 1544 ], "doc_id": "2f29a4a6323783368c1160597feb0d31e710bffb8f3df64f28bc205d88de1698" }, { "range": [ 0, 342 ], "doc_id": "c7a17a8edafad008f36b5244fcd85b81d3cb50261f11ba6159fe1297112fb956" } ], "split_idx_start": 8032, "file_name": "pep-0410.txt", "_file_created_at": "2024-10-18T09:04:01.074298+00:00", "split_id": 6, "_file_size": 20703, "page_number": 1, "source_id": "0a5ffe8e2eae3b854132370ba3ee43c31cba6d88fb72c635690acb723fcadeae" }, "score": 0.019683837890625, "embedding": null, "file": { "id": "5eda3f1a-74b9-4887-9772-35ca44be1e99", "name": "pep-0410.txt" }, "result_id": "fd0e6f52-d944-4642-bc66-61b852960cc8" }, { "id": "66722fd08f8adab75357847e2d8ab324d6175816435c99063e2c2d8a96171d74", "content": "PEP: 500\nTitle: A protocol for delegating datetime methods to their tzinfo implementations\nVersion: $Revision$\nLast-Modified: $Date$\nAuthor: Alexander Belopolsky , Tim Peters \nDiscussions-To: datetime-sig@python.org\nStatus: Rejected\nType: Standards Track\nContent-Type: text/x-rst\nRequires: 495\nCreated: 08-Aug-2015\nResolution: https://mail.python.org/pipermail/datetime-sig/2015-August/000354.html\n\nAbstract\n========\n\nThis PEP specifies a new protocol (PDDM - \"A Protocol for Delegating\nDatetime Methods\") that can be used by concrete implementations of the\n``datetime.tzinfo`` interface to override aware datetime arithmetics,\nformatting and parsing. We describe changes to the\n``datetime.datetime`` class to support the new protocol and propose a\nnew abstract class ``datetime.tzstrict`` that implements parts of this\nprotocol necessary to make aware datetime instances to follow \"strict\"\narithmetic rules.\n\n\nRationale\n=========\n\nAs of Python 3.5, aware datetime instances that share a ``tzinfo``\nobject follow the rules of arithmetics that are induced by a simple\nbijection between (year, month, day, hour, minute, second,\nmicrosecond) 7-tuples and large integers. In this arithmetics, the\ndifference between YEAR-11-02T12:00 and YEAR-11-01T12:00 is always 24\nhours, even though in the US/Eastern timezone, for example, there are\n25 hours between 2014-11-01T12:00 and 2014-11-02T12:00 because the\nlocal clocks were rolled back one hour at 2014-11-02T02:00,\nintroducing an extra hour in the night between 2014-11-01 and\n2014-11-02.\n\nMany business applications require the use of Python's simplified view\nof local dates. No self-respecting car rental company will charge its\ncustomers more for a week that straddles the end of DST than for any\nother week or require that they return the car an hour early.\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 0, 185 ], "doc_id": "2491a8b58f7bb1979fdf5061006dfc72c54b6e9e287f06f9b8a5dd669967c874" } ], "split_idx_start": 0, "file_name": "pep-0500.txt", "_file_created_at": "2024-10-18T09:03:51.944443+00:00", "split_id": 0, "_file_size": 7045, "page_number": 1, "source_id": "5180621105b359308fb5b39c5455b227c26cb8533a69672335202ed14e8d568d" }, "score": 0.018798828125, "embedding": null, "file": { "id": "cf52312b-26b9-4ded-ac2b-cb6faf344a86", "name": "pep-0500.txt" }, "result_id": "623d6f02-476c-4110-83e9-92186bc055b9" }, { "id": "d9878e926481ac189a88db4f7ed36cb64cd9e28bd58c450ee11c2731dba935d6", "content": "One part is the proposal of a\nprotocol for objects to declare and provide support for exposing a\nfile system path representation. The other part deals with changes to\nPython's standard library to support the new protocol. These changes\nwill also lead to the pathlib module dropping its provisional status.\n\nProtocol\n--------\n\nThe following abstract base class defines the protocol for an object\nto be considered a path object::\n\n import abc\n import typing as t\n\n\n class PathLike(abc.ABC):\n\n \"\"\"Abstract base class for implementing the file system path protocol.\"\"\"@abc.abstractmethod\n def __fspath__(self) -> t.Union[str, bytes]:\n \"\"\"Return the file system path representation of the object.\"\"\"raise NotImplementedError\n\n\nObjects representing file system paths will implement the\n``__fspath__()`` method which will return the ``str`` or ``bytes``\nrepresentation of the path. The ``str`` representation is the\npreferred low-level path representation as it is human-readable and\nwhat people historically represent paths as.\n\n\nStandard library changes\n------------------------\n\nIt is expected that most APIs in Python's standard library that\ncurrently accept a file system path will be updated appropriately to\naccept path objects (whether that requires code or simply an update\nto documentation will vary). The modules mentioned below, though,\ndeserve specific details as they have either fundamental changes that\nempower the ability to use path objects, or entail additions/removal\nof APIs.\n\n\nbuiltins\n''''''''\n\n``open()`` [#builtins-open]_ will be updated to accept path objects as\nwell as continue to accept ``str`` and ``bytes``.\n\n\n", "content_type": "text", "meta": { "_split_overlap": [ { "range": [ 1308, 1615 ], "doc_id": "73e62bf9eacb2631fd3da8a9f98313919f5e6851cbc7fcd72f71b8e2ffb578d9" }, { "range": [ 0, 329 ], "doc_id": "e3149c5c7a835f78b529358fafabe007d0d109d48517de4314d5f6ad45534d7a" } ], "split_idx_start": 3824, "file_name": "pep-0519.txt", "_file_created_at": "2024-10-18T09:03:49.692777+00:00", "split_id": 3, "_file_size": 22105, "page_number": 1, "source_id": "cf21ac8366c79d9b83f9fc8a0efd4982b0d4d4e0ae7c2716a5eea2fca6bf00a9" }, "score": 0.0169219970703125, "embedding": null, "file": { "id": "a8a8d83e-6696-46c7-9ebf-3a953da41132", "name": "pep-0519.txt" }, "result_id": "85c4399f-38d4-439d-94b6-ffcfa7c52e67" } ], "_debug": null, "prompts": null } ] } ```
### Chain the Requests Here is a sample code that: 1. Calls the `Get Pipeline` endpoint. 2. Extracts the pipeline ID from the response and calls the `Create Search Session` endpoint to create a search session. 3. Uses the session ID from the response to start the chat using the `Chat` endpoint. ```python # Replace your API key and base URL API_KEY = "" BASE_URL = "https://api.cloud.deepset.ai/api/v1" WORKSPACE = "legal-chat" PIPELINE = "rag-chat" headers = { "accept": "application/json", "authorization": f"Bearer {API_KEY}", "content-type": "application/json" } def get_pipeline_id(): url = f"{BASE_URL}/workspaces/{WORKSPACE}/pipelines/{PIPELINE}" response = requests.get(url, headers=headers) if response.status_code == 200: return response.json()["pipeline_id"] else: raise Exception(f"Failed to get pipeline ID: {response.status_code}") def create_search_session(pipeline_id): url = f"{BASE_URL}/workspaces/{WORKSPACE}/search_sessions" data = { "pipeline_id": pipeline_id } response = requests.post(url, headers=headers, json=data) if response.status_code == 200: return response.json()["search_session_id"] else: raise Exception(f"Failed to create search session: {response.status_code}") def start_chat(search_session_id, query): url = f"{BASE_URL}/workspaces/{WORKSPACE}/pipelines/{PIPELINE}/chat" data = { "chat_history_limit": 3, "debug": False, "view_prompts": False, "queries": [query], "search_session_id": search_session_id } response = requests.post(url, headers=headers, json=data) return response.status_code, response.json() def main(): try: # Get the pipeline ID pipeline_id = get_pipeline_id() print(f"Pipeline ID: {pipeline_id}") # Create a search session search_session_id = create_search_session(pipeline_id) print(f"Search Session ID: {search_session_id}") # Start the chat query = 'How do you present datetime objects in human readable format?"?' status_code, response_data = start_chat(search_session_id, query) print(f"Chat Status Code: {status_code}") print("Chat Response:") print(json.dumps(response_data, indent=2)) except Exception as e: print(f"An error occurred: {str(e)}") if __name__ == "__main__": main() ``` ```curl #!/bin/bash API_KEY="" BASE_URL="https://api.cloud.deepset.ai/api/v1" WORKSPACE="peps" PIPELINE="rag-chat" # Get pipeline ID PIPELINE_ID=$(curl --silent --request GET \ --url "${BASE_URL}/workspaces/${WORKSPACE}/pipelines/${PIPELINE}" \ --header "accept: application/json" \ --header "authorization: Bearer ${API_KEY}" | jq -r .pipeline_id) echo "Pipeline ID: $PIPELINE_ID" # Create search session SEARCH_SESSION_ID=$(curl --silent --request POST \ --url "${BASE_URL}/workspaces/${WORKSPACE}/search_sessions" \ --header "accept: application/json" \ --header "authorization: Bearer ${API_KEY}" \ --header "content-type: application/json" \ --data "{\"pipeline_id\": \"$PIPELINE_ID\"}" | jq -r .search_session_id) echo "Search Session ID: $SEARCH_SESSION_ID" # Start chat curl --request POST \ --url "${BASE_URL}/workspaces/${WORKSPACE}/pipelines/${PIPELINE}/chat" \ --header "accept: application/json" \ --header "authorization: Bearer ${API_KEY}" \ --header "content-type: application/json" \ --data "{ \"chat_history_limit\": 3, \"debug\": false, \"view_prompts\": false, \"queries\": [ \"How do you present datetime objects in human readable format?\" ], \"search_session_id\": \"$SEARCH_SESSION_ID\" }" ``` ## Start a New Chat To start a new chat, you must first create a new search session and then start a chat using the ID of the newly created session. 1. Call the [Create Search Session](/docs/api/main/create-search-session-api-v-1-workspaces-workspace-name-search-sessions-post) endpoint. 2. Call the [Chat](/docs/api/main/chat-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-chat-post) endpoint providing the search session ID. ## Show Previous Chats Use the [Pipeline Search History](/docs/api/main/pipeline-search-history-api-v-1-workspaces-workspace-name-pipelines-pipeline-name-search-history-get) endpoint to display previous chats. Use this code snippet as a starting point for the request. Fill in: - the pipeline and workspace name (in the URL). - API key (in headers). ```python url = "https://api.cloud.deepset.ai/api/v1/workspaces/peps/pipelines/rag-chat/search_history" #peps is the workspace name, rag-chat is the pipeline name headers = { "accept": "application/json", "authorization": "Bearer " } response = requests.get(url, headers=headers) print(response.text) ``` ```curl curl --request GET \ --url https://api.cloud.deepset.ai/api/v1/workspaces/legal-chat/pipelines/rag-chat/search_history \ --header 'accept: application/json' \ --header 'authorization: Bearer ' ``` ## Example This is an example Python script that: 1. Gets the pipeline ID and starts a new chat in the search session. 2. Resets the newly created chat. 3. Retrieves and displays a list of previous chats. The script is available as Google Colab: [![Chat app in ](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1mpYYQnDp-1jyLGL9A1Ox4d8RkbkvZr-o?usp=sharing#scrollTo=hIyED_ku5JlX)