com.hw.langchain.chains.llm.LLMChain Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hw.langchain.chains.llm;
import com.hw.langchain.base.language.BaseLanguageModel;
import com.hw.langchain.chains.base.Chain;
import com.hw.langchain.prompts.base.BasePromptTemplate;
import com.hw.langchain.schema.LLMResult;
import com.hw.langchain.schema.PromptValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Chain to run queries against LLMs
*
* @author HamaWhite
*/
public class LLMChain extends Chain {
private static final Logger LOG = LoggerFactory.getLogger(LLMChain.class);
protected BaseLanguageModel llm;
/**
* Prompt object to use.
*/
protected BasePromptTemplate prompt;
protected String outputKey = "text";
public LLMChain(BaseLanguageModel llm, BasePromptTemplate prompt) {
this.llm = llm;
this.prompt = prompt;
}
public LLMChain(BaseLanguageModel llm, BasePromptTemplate prompt, String outputKey) {
this.llm = llm;
this.prompt = prompt;
this.outputKey = outputKey;
}
@Override
public String chainType() {
return "llm_chain";
}
/**
* Will be whatever keys the prompt expects.
*/
@Override
public List inputKeys() {
return prompt.getInputVariables();
}
/**
* Will always return text key.
*/
@Override
public List outputKeys() {
return List.of(outputKey);
}
@Override
public Map _call(Map inputs) {
LLMResult response = generate(List.of(inputs));
return createOutputs(response).get(0);
}
/**
* Generate LLM result from inputs.
*/
private LLMResult generate(List