Azure OpenAI
これは、Microsoft Azure SDKを使用するAzure OpenAI
統合のドキュメントで、Microsoft Javaスタック(高度なAzure認証メカニズムを含む)を使用している場合に最適です。
LangChain4jはチャットモデルを使用するためのOpenAIとの4つの異なる統合を提供しており、これは#3です:
- OpenAIは、OpenAI REST APIのカスタムJava実装を使用し、Quarkus(Quarkus RESTクライアントを使用)とSpring(SpringのRestClientを使用)で最適に動作します。
- OpenAI公式SDKは、OpenAIの公式Java SDKを使用します。
- Azure OpenAIは、Microsoft Azure SDKを使用し、高度なAzure認証メカニズムを含むMicrosoft Javaスタックを使用している場合に最適です。
- GitHubモデルは、GitHub ModelsにアクセスするためにAzure AI推論APIを使用します。
Azure OpenAIは、Azure OpenAI Java SDKを使用して、Azure上でホストされているOpenAIの言語モデル(gpt-4
、gpt-4o
など)を提供します。
Azure OpenAIドキュメント
Maven依存関係
通常のJava
langchain4j-azure-open-ai
ライブラリはMaven Centralで利用可能です。
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-azure-open-ai</artifactId>
<version>1.0.0-beta4</version>
</dependency>
Spring Boot
Spring Bootスターターを使用すると、langchain4j-azure-open-ai
ライブラリをより簡単に設定できます。
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-azure-open-ai-spring-boot-starter</artifactId>
<version>1.0.0-beta4</version>
</dependency>
Azure OpenAIモデルを使用する前に、それらをデプロイする必要があります。
APIキーを使用したAzureOpenAiChatModel
の作成
通常のJava
ChatModel model = AzureOpenAiChatModel.builder()
.endpoint(System.getenv("AZURE_OPENAI_URL"))
.apiKey(System.getenv("AZURE_OPENAI_KEY"))
.deploymentName("gpt-4o")
...
.build();
これにより、デフォルトのモデルパラメータ(例:温度0.7
など)とAZURE_OPENAI_KEY
環境変数に格納されたAPIキーを持つAzureOpenAiChatModel
のインスタンスが作成されます。
デフォルトのモデルパラメータは、ビルダーで値を提供することでカスタマイズできます。
Spring Boot
application.properties
に追加:
langchain4j.azure-open-ai.chat-model.endpoint=${AZURE_OPENAI_URL}
langchain4j.azure-open-ai.chat-model.service-version=...
langchain4j.azure-open-ai.chat-model.api-key=${AZURE_OPENAI_KEY}
langchain4j.azure-open-ai.chat-model.non-azure-api-key=${OPENAI_API_KEY}
langchain4j.azure-open-ai.chat-model.deployment-name=gpt-4o
langchain4j.azure-open-ai.chat-model.max-tokens=...
langchain4j.azure-open-ai.chat-model.temperature=...
langchain4j.azure-open-ai.chat-model.top-p=
langchain4j.azure-open-ai.chat-model.logit-bias=...
langchain4j.azure-open-ai.chat-model.user=
langchain4j.azure-open-ai.chat-model.stop=...
langchain4j.azure-open-ai.chat-model.presence-penalty=...
langchain4j.azure-open-ai.chat-model.frequency-penalty=...
langchain4j.azure-open-ai.chat-model.seed=...
langchain4j.azure-open-ai.chat-model.strict-json-schema=...
langchain4j.azure-open-ai.chat-model.timeout=...
langchain4j.azure-open-ai.chat-model.max-retries=...
langchain4j.azure-open-ai.chat-model.log-requests-and-responses=...
langchain4j.azure-open-ai.chat-model.user-agent-suffix=
langchain4j.azure-open-ai.chat-model.custom-headers=...
上記のパラメータの一部の説明はこちらで確認できます。
この設定により、AzureOpenAiChatModel
ビーン(デフォルトのモデルパラメータを持つ)が作成され、
AIサービスで使用するか、
必要な場所でオートワイヤすることができます。例えば:
@RestController
class ChatModelController {
ChatModel chatModel;
ChatModelController(ChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/model")
public String model(@RequestParam(value = "message", defaultValue = "Hello") String message) {
return chatModel.chat(message);
}
}
Azure認証情報を使用したAzureOpenAiChatModel
の作成
APIキーにはいくつかのセキュリティ問題(コミットされる可能性、共有される可能性など)があります。
セキュリティを向上させたい場合は、代わりにAzure認証情報を使用することをお勧めします。
そのためには、プロジェクトにazure-identity
依存関係を追加する必要があります。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<scope>compile</scope>
</dependency>
その後、DefaultAzureCredentialBuilder APIを使用してAzureOpenAiChatModel
を作成できます:
ChatModel model = AzureOpenAiChatModel.builder()
.deploymentName("gpt-4o")
.endpoint(System.getenv("AZURE_OPENAI_URL"))
.tokenCredential(new DefaultAzureCredentialBuilder().build())
.build();
マネージドIDを使用してモデルをデプロイする必要があることに注意してください。詳細については、Azure CLIデプロイメントスクリプトを確認してください。
ツール
ツール(「関数呼び出し」とも呼ばれる)はサポートされており、モデルがJavaコード内のメソッドを呼び出すことを可能にします。並列ツール呼び出しも含まれます。 「関数呼び出し」はOpenAIのドキュメントでこちらに説明されています。
LangChain4jでの「関数呼び出し」の使用方法に関する完全なチュートリアルはこちらにあります。
関数はToolSpecification
クラスを使用して指定できますが、次の例のように@Tool
アノテーションを使用するとより簡単です:
class StockPriceService {
private Logger log = Logger.getLogger(StockPriceService.class.getName());
@Tool("Get the stock price of a company by its ticker")
public double getStockPrice(@P("Company ticker") String ticker) {
log.info("Getting stock price for " + ticker);
if (Objects.equals(ticker, "MSFT")) {
return 400.0;
} else {
return 0.0;
}
}
}
Then, you can use the StockPriceService
in an AI Assistant
like this:
interface Assistant {
String chat(String userMessage);
}
public class Demo {
String functionCalling(Model model) {
String question = "Is the current Microsoft stock higher than $450?";
StockPriceService stockPriceService = new StockPriceService();
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(stockPriceService)
.build();
String answer = assistant.chat(question);
model.addAttribute("answer", answer);
return "demo";
}
}
Structured Outputs
Structured Outputs ensure that a model's responses adhere to a JSON schema.
The documentation for using Structured Outputs in LangChain4j is available here, and in the section below you will find Azure OpenAI-specific information.
The model needs to be configured with the strictJsonSchema
parameter set to true
in order to force the adherence to a JSON Schema:
ChatModel model = AzureOpenAiChatModel.builder()
.endpoint(System.getenv("AZURE_OPENAI_URL"))
.apiKey(System.getenv("AZURE_OPENAI_KEY"))
.deploymentName("gpt-4o")
.strictJsonSchema(true)
.supportedCapabilities(Set.of(RESPONSE_FORMAT_JSON_SCHEMA))
.build();
If strictJsonSchema
is set to false
and you provide a JSON Schema, the model will still try to generate a response that adheres to the schema, but it will not fail if the response does not adhere to the schema. One reason to do this is for better performance.
You can then use this model either with the high level Assistant
API or the low level ChatModel
API, as detailed below.
When using it with the high level Assistant
API, configure supportedCapabilities(Set.of(RESPONSE_FORMAT_JSON_SCHEMA))
to enable structured outputs with a JSON schema.