Rechercher

Article
· Juil 24, 2024 4m de lecture

d[IA]gnosis: desarrollando aplicaciones RAG con IRIS for Health

Con la introducción de los tipos de datos vectoriales y la funcionalidad de Vector Search en IRIS se nos abre todo un mundo de posibilidades para el desarrollo de aplicaciones y un ejemplo de estas aplicaciones es la que vi reciéntemente publicada un concurso público de la Consejería de Sanidad de Valencia en la que solicitaban una herramienta para ayudar en la codificación CIE-10 utilizando modelos de IA.

¿Cómo podríamos implementar una aplicación similar a la solicitada? Veamos que necesitaríamos:

  1. Listado de códigos CIE-10, que usaremos como contexto de nuestra aplicación RAG para buscar diagnósticos dentro de los textos libres.
  2. Un modelo entrenado que nos vectorice los textos en los que vamos a buscar equivalencias en los códigos CIE-10.
  3. Las librerías Python necesarias para la ingesta y vectorización de los códigos CIE-10 y los textos.
  4. Un front-end amigable que admita textos sobre los que busquemos posibles diagnósticos.
  5. Orquestación de las solicitudes recibidas desde el front-end.

¿Qué nos proporciona IRIS para cubrir las necesidades anteriores?

  1. Importación de CSV, ya sea usando la funcionalidad de RecordMapper o directamente usando Embedded Python.
  2. Embedded Python nos permite implementar el código Python necesario para generar los vectores haciendo uso del modelo seleccionado.
  3. Publicación de APIs REST a las que se invocará desde la aplicación de front-end.
  4. Producciones de interoperabilidad que permiten el seguimiento de la información dentro de IRIS.

Pues sólo nos queda ver el ejemplo desarrollado:

d[IA]gnosis

Asociado a este artículo tenéis el acceso a la aplicación desarrollada, en los próximos artículos veremos en detalle como implementamos cada una de las funcionalidades, desde la utilización del modelo, el almacenamiento de los vectores y la utilización de las búsquedas vectoriales.

Revisemos la aplicación:

Importando códigos CIE-10

Desde la pantalla de configuración se nos indica el formato que debe seguir el archivo CSV con los códigos CIE-10 que vamos a importar, el proceso de carga y vectorización consume bastante tiempo y recursos, por ello el despliegue del contenedor Docker configura no sólo la memoria RAM utilizable por Docker sino que también la memoria de disco en caso de que los requerimientos superen la RAM asignada:

  # iris
  iris:
    init: true
    container_name: iris
    build:
      context: .
      dockerfile: iris/Dockerfile
    ports:
      - 52774:52773
      - 51774:1972
    volumes:
    - ./shared:/shared
    environment:
    - ISC_DATA_DIRECTORY=/shared/durable
    command: --check-caps false --ISCAgent false
    mem_limit: 30G
    memswap_limit: 32G

El archivo con los códigos CIE-10 está disponible en la ruta del proyecto /shared/cie10/cie10.csv, una vez alcanzado el 100% la aplicación estará lista para ser utilizada.

En nuestra aplicación hemos definido dos funcionalidades distintas para la codificación de diagnósticos, una a partir de los mensajes HL7 recibidos en el sistema y otra basada en textos libres.

Captura de diagnósticos mediante HL7

El proyecto contiene una serie de mensajes de HL7 preparados para realizar pruebas, sólo es necesario copiar el archivo /shared/hl7/messagesa01.hl7 a la carpeta /shared/HL7In y la producción asociada se encargará de extraer el diagnóstico del mismo para mostrarlo en la aplicación web:

Desde la pantalla de solicitudes de diagnóstico podremos ver todos los diagnósticos recibidos vía mensajería HL7, para su codificación a CIE-10 sólo necesitamos pulsar en lupa para mostrar un listado de aquellos códigos CIE-10 más próximo al diagnóstico recibido:

Una vez seleccionado veremos en el listado el diagnóstico y su código CIE-10 asociado, pulsando en el botón con el icono del sobre se generará un mensaje usando el original e incluyendo dentro del segmento del diagnóstico el nuevo seleccionado:

MSH|^~\&|HIS|HULP|EMPI||||ADT^A08|592956|P|2.5.1
EVN|A01|
PID|||1556655212^^^SERMAS^SN~922210^^^HULP^PI||GARCÍA PÉREZ^JUAN^^^||20150403|M|||PASEO PEDRO ÁLVAREZ 195 1 CENTRO^^LEGANÉS^MADRID^28379^SPAIN||555283055^PRN^^JUAN.GARCIA@YAHOO.COM|||||||||||||||||N|
PV1||N
DG1|1||O16.9^Hipertensión materna no especificada, trimestre no especificado^CIE10-ES|Hipertensión gestacional||A||

Dicho mensaje se podrá encontrar en la ruta /shared/HL7Out

Capturas de diagnósticos en texto libre

Desde la opción de Analizador de texto el usuario podrá incluir un texto libre sobre el que se realizará un proceso de análisis. La aplicación buscará en tuplas de 3 palabras lematizadas (eliminando artículos, pronombres y demás palabras poco relavantes). Una vez analizadas el sistema nos mostrará el texto relevante subrayado y los posibles diagnósticos localizados:

Una vez realizado el análisis este podrá ser consultado en cualquier momento desde el histórico de análisis.

Histórico de análisis

Todos los análisis realizados quedan registrados y podrán ser consultados en cualquier momento, pudiendo visualizar todos los posibles códigos CIE-10 disponibles:

En el próximo artículo...

Veremos como mediante Embedded Python utilizamos un modelo LLM específico para la vectorización tanto de los códigos CIE-10 que usaremos como contexto como de los textos libres.

Si tenéis cualquier pregunta o sugerencia no dudéis en escribir un comentario en el artículo.

6 Comments
Discussion (6)3
Connectez-vous ou inscrivez-vous pour continuer
Question
· Juil 24, 2024

Mapping Between Management Portal Components and Object Script

Is there documentation that shows the mapping between the management portal components and object script package.class.methods? 
I am searching on-line documentation but have not been successful.
For example, in the management portal  SystemOperation > TaskManager > TaskSchedule  can map to the method:  class(Monitors.Tasks).ListSuspendedTasks().


What would be a similar mapping for SystemOperation > TaskManager > TaskHistory?
I initially thought it would be something similar to class(Monitors.Tasks).ListTaskHistory().

Best Regards,

1 Comment
Discussion (1)1
Connectez-vous ou inscrivez-vous pour continuer
Question
· Juil 24, 2024

Undocumented RoutineList features

As I was trying to create a routine search query via RoutineList, I discovered that documentation both for Cache and Iris offers only ABC* and ABC? syntax for including routine names and, unlike %RO, does not offer name ranges. Is that indeed so?

After some system files reading, I discovered that you can EXCLUDE certain routines with ', by using the 'ABC or 'ABC* syntax. That is not documented but it should be. Any other non-documented RoutineList syntax capabilities? 

Example:

list="ABC*,'ABCD*,XYZ"
;Iterate through routine list
rs=##class(%ResultSet).%New("%Routine:RoutineList")
x=rs.Execute(list)
t=""
F  {
x=rs.Next() q:'x
rtnName=rs.GetData(1)
rtnName,","
}

1 Comment
Discussion (1)2
Connectez-vous ou inscrivez-vous pour continuer
Article
· Juil 24, 2024 2m de lecture

XML export of Studio project unexpectedly omits webapp (CSP) files when webapp name doesn't contain any slashes

I encountered this quirk when investigating an unrelated issue affecting how Studio projects are handled in VS Code.

When you add the top level of the webapp to a %Studio.Project this inserts a %Studio.ProjectItem with a .DIR suffix. For example, if Studio or VS Code is connected to the USER namespace and you add the /csp/user webapp to a project the new ProjectItem name is "csp/user.DIR".

When you export this project to XML from the project's context menu in Studio, or by calling the %Studio.Project.Export classmethod, the file contains the project definition plus all of the files in the /csp/user webapp's physical path subtree (i.e. all your CSP, JavaScript, CSS etc files). Importing this to a namespace on another server on which a webapp of the same name exists is a convenient way of transferring the webapp's code.

The quirk/bug is that if your webapp name doesn't contain any slashes (ignoring the leading one that begins all webapp names), then the Export classmethod fails to put the webapp's files into its XML output file.

For example, if the namespace MYAPP hosts a webapp named /myapp and you create a Studio project consisting of "myapp.DIR" as its ProjectItem, an export of this project doesn't contain your webapp's files.

Here's why this happens:

Line 871 calls the Exists method of %Library.RoutineMgr with the argument "myapp.DIR"

The code at line 653 above is apparently there to ensure that names of webapp files or directories have a "/" prefix before being used in calls to $$GetFilename^%apiCSP on line 661 (for .DIR items) or to ..IsCSPName on line 664 (everything else).

But for a .DIR item without a slash within it (e.g. "myapp.DIR" as opposed to "csp/user.DIR", line 653 is ineffective and Exists("myapp.DIR") returns 0.

This could be fixed by moving line 657 ahead of line 653, then amending that line (now 654) to add ext="dir" to the existing OR conditions. However the entire %Studio package no longer appears in the latest Class Reference (aka Documatic), so I reckon the chances of this getting fixed are low, and of being backported even lower. I'm posting the information here in case it's useful to anyone else. A workaround is not to use webapp names that have a single path component.

2 Comments
Discussion (2)2
Connectez-vous ou inscrivez-vous pour continuer
Annonce
· Juil 24, 2024

InterSystems Ideas News #15

Hi Developers!

Welcome to the 15th edition of the InterSystems Ideas news! We dedicate this news bulletin to:

​​​​✓ Idea Leaders of 2024

✓ Voting for ideas on Open Exchange

✓ Recently posted ideas waiting to be implemented by the Developer Community

 
   In a bit more than half a year, quite a few of Community members have submitted their ideas to the Ideas Portal. We extend our heartfelt thanks to all contributors and want to give a special shout-out to the authors who have shared numerous ideas on the portal this year.

Your creativity and dedication are truly inspiring! 👏

 You can now vote for ideas that can be implemented by Developer Community members not only on the Ideas Portal but also on the Open Exchange. In the special window (look below for an example screenshot), you can click on the "Vote" button to support the idea. You will see a random Community Opportunity idea whenever you visit Open Exchange.

👏 Many thanks to the authors of these ideas👏

💡 Thank you for reading InterSystems Ideas news. Post your innovative ideas, vote for ideas to support them and implement Community Opportunity ideas to join our Hall of Fame 💡

Discussion (0)1
Connectez-vous ou inscrivez-vous pour continuer