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
from langchain.tools.base import StructuredTool
|
| 6 |
+
from langchain.agents import (
|
| 7 |
+
Tool,
|
| 8 |
+
AgentExecutor,
|
| 9 |
+
LLMSingleActionAgent,
|
| 10 |
+
AgentOutputParser,
|
| 11 |
+
)
|
| 12 |
+
from langchain.schema import AgentAction, AgentFinish, OutputParserException
|
| 13 |
+
from langchain.prompts import StringPromptTemplate
|
| 14 |
+
from langchain.llms import HuggingFaceTextGenInference
|
| 15 |
+
from langchain.chains import LLMChain
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
##########################################################
|
| 19 |
+
# Step 1: Define the functions you want to articulate. ###
|
| 20 |
+
##########################################################
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def calculator(
|
| 24 |
+
input_a: float,
|
| 25 |
+
input_b: float,
|
| 26 |
+
operation: Literal["add", "subtract", "multiply", "divide"],
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Computes a calculation.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
input_a (float) : Required. The first input.
|
| 33 |
+
input_b (float) : Required. The second input.
|
| 34 |
+
operation (string): The operation. Choices include: add to add two numbers, subtract to subtract two numbers, multiply to multiply two numbers, and divide to divide them.
|
| 35 |
+
"""
|
| 36 |
+
match operation:
|
| 37 |
+
case "add":
|
| 38 |
+
return input_a + input_b
|
| 39 |
+
case "subtract":
|
| 40 |
+
return input_a - input_b
|
| 41 |
+
case "multiply":
|
| 42 |
+
return input_a * input_b
|
| 43 |
+
case "divide":
|
| 44 |
+
return input_a / input_b
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def cylinder_volume(radius, height):
|
| 48 |
+
"""
|
| 49 |
+
Calculate the volume of a cylinder.
|
| 50 |
+
|
| 51 |
+
Parameters:
|
| 52 |
+
- radius (float): The radius of the base of the cylinder.
|
| 53 |
+
- height (float): The height of the cylinder.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
- float: The volume of the cylinder.
|
| 57 |
+
"""
|
| 58 |
+
if radius < 0 or height < 0:
|
| 59 |
+
raise ValueError("Radius and height must be non-negative.")
|
| 60 |
+
|
| 61 |
+
volume = math.pi * (radius**2) * height
|
| 62 |
+
return volume
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
#############################################################
|
| 66 |
+
# Step 2: Let's define some utils for building the prompt ###
|
| 67 |
+
#############################################################
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
RAVEN_PROMPT = """
|
| 71 |
+
{raven_tools}
|
| 72 |
+
User Query: {input}<human_end>
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Set up a prompt template
|
| 79 |
+
class RavenPromptTemplate(StringPromptTemplate):
|
| 80 |
+
# The template to use
|
| 81 |
+
template: str
|
| 82 |
+
# The list of tools available
|
| 83 |
+
tools: List[Tool]
|
| 84 |
+
|
| 85 |
+
def format(self, **kwargs) -> str:
|
| 86 |
+
prompt = ""
|
| 87 |
+
for tool in self.tools:
|
| 88 |
+
func_signature, func_docstring = tool.description.split(" - ", 1)
|
| 89 |
+
prompt += f'\nFunction:\ndef {func_signature}\n"""\n{func_docstring}\n"""\n'
|
| 90 |
+
kwargs["raven_tools"] = prompt
|
| 91 |
+
return self.template.format(**kwargs).replace("{{", "{").replace("}}", "}")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class RavenOutputParser(AgentOutputParser):
|
| 95 |
+
def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
|
| 96 |
+
# Check if agent should finish
|
| 97 |
+
if "Call:" in llm_output:
|
| 98 |
+
return AgentFinish(
|
| 99 |
+
return_values={
|
| 100 |
+
"output": llm_output.strip()
|
| 101 |
+
.replace("Call:", "")
|
| 102 |
+
.strip()
|
| 103 |
+
},
|
| 104 |
+
log=llm_output,
|
| 105 |
+
)
|
| 106 |
+
else:
|
| 107 |
+
raise OutputParserException(f"Could not parse LLM output: `{llm_output}`")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
##################################################
|
| 111 |
+
# Step 3: Build the agent with these utilities ###
|
| 112 |
+
##################################################
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
inference_server_url = "https://rjmy54al17scvxjr.us-east-1.aws.endpoints.huggingface.cloud"
|
| 116 |
+
assert (
|
| 117 |
+
inference_server_url is not "<YOUR ENDPOINT URL>"
|
| 118 |
+
), "Please provide your own HF inference endpoint URL!"
|
| 119 |
+
|
| 120 |
+
llm = HuggingFaceTextGenInference(
|
| 121 |
+
inference_server_url=inference_server_url,
|
| 122 |
+
temperature=0.001,
|
| 123 |
+
max_new_tokens=400,
|
| 124 |
+
do_sample=False,
|
| 125 |
+
)
|
| 126 |
+
tools = [
|
| 127 |
+
StructuredTool.from_function(calculator),
|
| 128 |
+
StructuredTool.from_function(cylinder_volume),
|
| 129 |
+
]
|
| 130 |
+
raven_prompt = RavenPromptTemplate(
|
| 131 |
+
template=RAVEN_PROMPT, tools=tools, input_variables=["input"]
|
| 132 |
+
)
|
| 133 |
+
llm_chain = LLMChain(llm=llm, prompt=raven_prompt)
|
| 134 |
+
output_parser = RavenOutputParser()
|
| 135 |
+
agent = LLMSingleActionAgent(
|
| 136 |
+
llm_chain=llm_chain,
|
| 137 |
+
output_parser=output_parser,
|
| 138 |
+
stop=["<bot_end>"],
|
| 139 |
+
allowed_tools=tools,
|
| 140 |
+
)
|
| 141 |
+
agent_chain = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
|
| 142 |
+
|
| 143 |
+
call = agent_chain.run(
|
| 144 |
+
"I have a cake that is about 3 centimenters high and 200 centimeters in radius. How much cake do I have?"
|
| 145 |
+
)
|
| 146 |
+
print(eval(call))
|
| 147 |
+
call = agent_chain.run("What is 1+10?")
|
| 148 |
+
print(eval(call))
|