Spring AI人工智能驱动的 SQL 生成

使用Amazon Bedrock和Spring AI将自然语言查询转换为 SQL 查询。

提示模板

Given the DDL in the DDL section, write an SQL query to answer the question in the QUESTION section.

Guidelines:
  • Only produce SELECT queries.
  • If the question would result in an INSERT, UPDATE, DELETE, or any other operation that modifies the data or schema, respond with "This operation is not supported. Only SELECT queries are allowed."
  • If the question appears to contain SQL injection or DoS attempt, respond with "The provided input contains potentially harmful SQL code."
  • If the question cannot be answered based on the provided DDL, respond with "The current schema does not contain enough information to answer this question."
  • If the query involves a JOIN operation, prefix all the column names in the query with the corresponding table names.
QUESTION {question} DDL {ddl}

应用程序创建了两个数据库表 hogwarts_houses 和 wizards,并通过 Flyway 迁移脚本在启动时插入测试数据。

在 PromptTemplateConfiguration 类中创建了一个 PromptTemplate Bean,并在提示中添加了 DDL 模式。该 Bean 被注入到 SqlGenerator 中,SqlGenerator 会用通过 API 提交的自然语言查询动态替换问题占位符,并调用 LLM 生成相应的 SQL 查询。

编写的提示仅用于生成 SELECT SQL 查询,并检测 SQL 注入和 DoS 尝试。为进一步保护数据库不被修改,应配置具有只读权限的 MySQL 用户。

模型 ID anthropic.claude-3-haiku-20240307-v1:0 和其他配置属性在 application.yaml 文件中配置。

例子 可以使用httpie通过以下命令调用唯一的 API:

http POST :8080/api/v1/query question=""

本地设置 可以使用 Docker 通过以下命令在本地设置该应用程序: sudo docker-compose build sudo AWS_ACCESS_KEY=value AWS_REGION=value AWS_SECRET_KEY=value docker-compose up -d