import java.util.HashMap;
import java.util.Map;
public class PeopleAddressList { private Map<String, String> addressList; public PeopleAddressList() { addressList = new HashMap<>(); }
public void addPerson(String name, String address) { addressList.put(name, address); }
public String getAddress(String name) { return addressList.get(name); }
public void removePerson(String name) { addressList.remove(name); }
public int size() { return addressList.size(); }
public void clear() { addressList.clear(); }
public void printAddressList() { for (String name : addressList.keySet()) { System.out.println(name + ” : ” + addressList.get(name)); } }
public static void main(String[] args) { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);
list.addPerson(“Jane Doe”, “456 Elm Street”); list.printAddressList(); }}
//Main class as below
import java.util.HashMap;
import java.util.Map;
public class AddressSummary {
private PeopleAddressList addressList; public void setAddressList(PeopleAddressList addressList) { this.addressList = addressList; }
public String toString() { StringBuilder sb = new StringBuilder(); for (String name : addressList.keySet()) { sb.append(name + ” : ” + addressList.get(name) + “\n”); } return sb.toString(); }
public static void main(String[] args) { AddressGeneration generation = new AddressGeneration(); PeopleAddressList list = generation.getPeopleAddressList(); AddressSummary summary = new AddressSummary(); summary.setAddressList(list); System.out.println(summary); }}
public class AddressGeneration {
public PeopleAddressList getPeopleAddressList() { PeopleAddressList list = new PeopleAddressList(); list.addPerson(“John Doe”, “123 Main Street”);
list.addPerson(“Jane Doe”, “456 Elm Street”);
return list; }}
//Facade Design pattern
import java.util.HashMap;
import java.util.Map;
public class AddressSummaryFacade {
private AddressGeneration generation;
private AddressSummary summary;
public AddressSummaryFacade() {
generation = new AddressGeneration();
summary = new AddressSummary();
}
public String getAddressSummary() {
summary.setAddressList(generation.getPeopleAddressList());
return summary.toString();
}
}
public class Main {
public static void main(String[] args) {
AddressSummaryFacade facade = new AddressSummaryFacade();
System.out.println(facade.getAddressSummary());
}
}
tablesaw vs apachepoi
import org.apache.poi.ss.usermodel.*;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import tech.tablesaw.api.Table;import org.openjdk.jmh.annotations.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;@BenchmarkMode(Mode.Throughput)@Warmup(iterations = 3, time = 1)@Measurement(iterations = 5, time = 1)@State(Scope.Benchmark)public class ExcelReadBenchmark { private File excelFile; private Table tablesawTable; @Setup public void setup() { // Initialize your Excel file and Tablesaw table here excelFile = new File(“your-excel-file.xlsx”); // Replace with your Excel file path tablesawTable = Table.read().csv(“your-csv-file.csv”); // Replace with your CSV file path } @Benchmark public void readAndPrintWithTablesaw() { // Perform reading and printing using Tablesaw String column1 = tablesawTable.column(“Column1”).toString(); // Print or process column1 here } @Benchmark public void readAndPrintWithApachePOI() throws IOException { // Perform reading and printing using Apache POI FileInputStream inputStream = new FileInputStream(excelFile); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet for (Row row : sheet) { Cell cell = row.getCell(0); // Access the first cell (column 1) if (cell != null) { String cellValue = cell.toString(); // Print or process cellValue here } } workbook.close(); inputStream.close(); } public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); }}
read from 100 to 200
import tech.tablesaw.api.*;
import tech.tablesaw.io.csv.CsvReadOptions;
public class ReadCSVWithTablesaw {
public static void main(String[] args) {
// Define the path to your CSV file
String csvFilePath = "path/to/your/file.csv"; // Replace with your CSV file path
// Define the range of rows you want to read (100 to 200)
int startRow = 100;
int endRow = 200;
try {
// Define read options
CsvReadOptions options = CsvReadOptions.builder(csvFilePath)
.header(true) // Assuming the CSV file has a header row
.build();
// Read the CSV file into a Table
Table table = Table.read().csv(options);
// Extract the desired rows (100 to 200) from column 1
Column<String> column1 = table.column(1).subList(startRow, endRow + 1).asStringColumn();
// Print or process the values in column1
for (String value : column1) {
System.out.println(value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// SpringBoot
//YourService
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class YourService {
public Mono<Address> fetchAddress(String branch, String filename) {
return WebClient.create()
.get()
.uri("https://bitbucket.org/{filename}?branch={branch}")
.retrieve()
.bodyToMono(String.class)
.map(json -> parseAddressFromJson(json)); // Custom parsing logic
}
private Address parseAddressFromJson(String json) {
// Implement your JSON parsing logic to convert JSON string to Address object
// For example, using Jackson ObjectMapper:
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(json, Address.class);
} catch (JsonProcessingException e) {
// Handle parsing exception
throw new RuntimeException("Error parsing JSON", e);
}
}
}
//Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping(“/api/addresses”)
public class AddressController {
private final YourService yourService;
@Autowired
public AddressController(YourService yourService) {
this.yourService = yourService;
}
@GetMapping("/{branch}/{filename}")
public Mono<ResponseEntity<Address>> getAddress(
@PathVariable String branch,
@PathVariable String filename) {
return yourService.fetchAddress(branch, filename)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
}
// Detailed implementation
//AddressService
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.io.IOException;
@Service
public class AddressService {
private final WebClient webClient;
private final String repositoryUrl;
private final String branch;
public AddressService(WebClient.Builder webClientBuilder,
@Value("${bitbucket.repositoryUrl}") String repositoryUrl,
@Value("${bitbucket.branch}") String branch) {
this.webClient = webClientBuilder.build();
this.repositoryUrl = repositoryUrl;
this.branch = branch;
}
public Mono<Address> getAddressFromBitbucket(String filename) {
// Construct the URL to the JSON file in the Bitbucket repository
String url = String.format("%s/%s/%s/%s", repositoryUrl, branch, filename);
// Make a GET request using WebClient
return webClient.get()
.uri(url)
.retrieve()
.bodyToMono(String.class)
.flatMap(this::parseAddressFromJson);
}
private Mono<Address> parseAddressFromJson(String jsonResponse) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode jsonNode = mapper.readTree(jsonResponse);
// Extract address data from the JSON node
Address address = new Address();
address.setStreet(jsonNode.get("street").asText());
address.setCity(jsonNode.get("city").asText());
address.setState(jsonNode.get("state").asText());
address.setCountry(jsonNode.get("country").asText());
address.setPostalCode(jsonNode.get("postalCode").asText());
return Mono.just(address);
} catch (IOException e) {
return Mono.error(e);
}
}
}
// app prop / yaml
bitbucket.repositoryUrl=https://api.bitbucket.org/2.0/repositories/{username}/{repo_slug}/src
bitbucket.branch=master
// your service
@Service
public class YourService {
private final AddressService addressService;
public YourService(AddressService addressService) {
this.addressService = addressService;
}
public Mono<Address> getAddress(String filename) {
return addressService.getAddressFromBitbucket(filename);
}
}
// controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping(“/api”)
public class AddressController {
private final YourService yourService;
@Autowired
public AddressController(YourService yourService) {
this.yourService = yourService;
}
@GetMapping("/address/{filename}")
public Mono<ResponseEntity<Address>> getAddress(@PathVariable String filename) {
return yourService.getAddress(filename)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
}
Addl java examples
@Service
public class BitbucketService {
private final WebClient webClient;
public BitbucketService() {
webClient = WebClient.builder()
.baseUrl("https://api.bitbucket.org/2.0/")
.build();
}
public String getJsonFile() {
String repoOwner = "your-repo-owner";
String repoName = "your-repo-name";
String filePath = "path/to/your/json/file.json";
String url = String.format("repos/%s/%s/contents/%s", repoOwner, repoName, filePath);
return webClient.get().uri(url).retrieve().bodyToMono(String.class).block();
}
}
@RestController
public class JsonController {
private final BitbucketService bitbucketService;
public JsonController(BitbucketService bitbucketService) {
this.bitbucketService = bitbucketService;
}
@GetMapping("/json")
public String getJson() {
return bitbucketService.getJsonFile();
}
}
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.fasterxml.jackson.databind.ObjectMapper; // For JSON parsing
public class JsonReader {
public static void main(String[] args) {
String jsonUrl = “https://your_git_repo_url/abc.json”; // Replace with your file’s URL
try {
URL url = new URL(jsonUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String jsonString = reader.lines().collect(Collectors.joining());
reader.close();
// Deserialize JSON (assuming you have a suitable class 'MyData')
ObjectMapper mapper = new ObjectMapper();
MyData dataObject = mapper.readValue(jsonString, MyData.class);
System.out.println(dataObject); // Access your data
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java excel reader
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelUpdater {
public static void main(String[] args) {
String excelFilePath = “path/to/your/excel-file.xlsx”; // Change to your Excel file path
try (FileInputStream fis = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheet(“Sheet1”);
// Loop through all rows in column A
for (int i = 0; i < 100; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cellA = row.getCell(0); // Column A
Cell cellB = row.getCell(1); // Column B
if (cellA != null && cellB != null) {
// Update Column A to match Column B
cellA.setCellValue(cellB.getStringCellValue());
}
}
}
// Write the changes back to the file
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
}
System.out.println(“Excel file updated successfully!”);
} catch (IOException e) {
e.printStackTrace();
}
}
}
SpringBoot examples
Git access logic
package com.web.client.demo.controller;
import com.web.client.demo.model.WorkflowRequest;
import com.web.client.demo.service.GitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
- Controller to handle Git and Gradle operations.
*/
@RestController
@RequestMapping(“/api/get”)
public class GitController { private final GitService gitService; @Autowired
public GitController(GitService gitService) {
this.gitService = gitService;
} /**- Endpoint to trigger the git clone/pull and gradle clean test workflow.
* - @param request The request containing Git repository URL and branch.
- @return The combined output of Git and Gradle commands.
*/
@PostMapping(“/execute-workflow”)
public ResponseEntity executeWorkflow(@RequestBody WorkflowRequest request) {
try {
String gitUrl = request.getGitUrl();
String branch = request.getBranch();// Define target directory (e.g., repositories will be cloned into a 'repos' folder in the current directory) String targetDir = "repos/" + extractRepoName(gitUrl); // Define project sub-directory (e.g., 'quality/services') String projectSubDir = "quality/services"; String output = gitService.executeWorkflow(gitUrl, branch, targetDir, projectSubDir); return ResponseEntity.ok(output);
} catch (RuntimeException e) {
return ResponseEntity.status(500).body(“Error: ” + e.getMessage());
}
}
- Extracts the repository name from the Git URL.
* - @param gitUrl The Git repository URL.
- @return The repository name.
*/
private String extractRepoName(String gitUrl) {
if (gitUrl == null || gitUrl.isEmpty()) {
throw new IllegalArgumentException(“Git URL cannot be null or empty.”);
}
// Remove trailing .git if present
gitUrl = gitUrl.endsWith(“.git”) ? gitUrl.substring(0, gitUrl.length() – 4) : gitUrl;
// Extract repository name
return gitUrl.substring(gitUrl.lastIndexOf(‘/’) + 1);
}
}
- Endpoint to trigger the git clone/pull and gradle clean test workflow.
package com.web.client.demo.model;
import lombok.Data;
@Data
public class WorkflowRequest {
private String gitUrl;
private String branch;
}
package com.web.client.demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@Service
public class GitService {
private static final Logger logger = LoggerFactory.getLogger(GitService.class);
/**
* Executes a shell command in a specific directory.
*
* @param command The command to execute.
* @param workingDir The directory in which to execute the command.
* @return The output of the command.
* @throws IOException If an I/O error occurs.
* @throws InterruptedException If the process is interrupted.
*/
private String executeCommand(String[] command, File workingDir) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(workingDir);
processBuilder.redirectErrorStream(true); // Merge error and output streams
logger.info("Executing command: {}", String.join(" ", command));
Process process = processBuilder.start();
// Read the output
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
logger.info(line);
}
}
// Wait for the process to complete
int exitCode = process.waitFor();
logger.info("Command exited with code: {}", exitCode);
if (exitCode != 0) {
throw new RuntimeException("Command " + String.join(" ", command) + " failed with exit code " + exitCode);
}
return output.toString();
}
/**
* Clones the Git repository if it doesn't exist, otherwise performs a git pull.
*
* @param gitUrl The URL of the Git repository.
* @param branch The branch to clone or pull.
* @param targetDir The directory where the repository should be cloned.
* @return The output of the git clone or git pull command.
*/
public String cloneOrPullRepo(String gitUrl, String branch, String targetDir) {
File repoDir = new File(targetDir);
try {
if (repoDir.exists()) {
logger.info("Repository already exists. Performing git pull.");
String[] pullCommand = {"git", "pull"};
return executeCommand(pullCommand, repoDir);
} else {
logger.info("Cloning repository.");
String[] cloneCommand = {"git", "clone", "-b", branch, gitUrl, targetDir};
return executeCommand(cloneCommand, repoDir.getParentFile());
}
} catch (IOException | InterruptedException e) {
logger.error("Error during git operation", e);
throw new RuntimeException("Git operation failed: " + e.getMessage(), e);
}
}
/**
* Executes the Gradle command in the specified directory.
*
* @param projectDir The directory where the Gradle command should be executed.
* @return The output of the Gradle command.
*/
public String runGradleCleanTest(String projectDir) {
File gradleDir = new File(projectDir);
try {
logger.info("Running Gradle clean test.");
String[] gradleCommand = {"./gradlew", "clean", "test", "--info"};
return executeCommand(gradleCommand, gradleDir);
} catch (IOException | InterruptedException e) {
logger.error("Error during Gradle operation", e);
throw new RuntimeException("Gradle operation failed: " + e.getMessage(), e);
}
}
/**
* Executes the full workflow: clone/pull Git repository and run Gradle tests.
*
* @param gitUrl The URL of the Git repository.
* @param branch The branch to clone or pull.
* @param targetDir The directory where the repository should be cloned.
* @param projectSubDir The sub-directory within the repository to run Gradle commands.
* @return The combined output of Git and Gradle commands.
*/
public String executeWorkflow(String gitUrl, String branch, String targetDir, String projectSubDir) {
StringBuilder combinedOutput = new StringBuilder();
// Step 1: Clone or Pull Git Repository
combinedOutput.append("=== Git Operation ===\n");
String gitOutput = cloneOrPullRepo(gitUrl, branch, targetDir);
combinedOutput.append(gitOutput).append("\n");
// Step 2: Run Gradle Clean Test
combinedOutput.append("=== Gradle Operation ===\n");
String gradleOutput = runGradleCleanTest(targetDir + File.separator + projectSubDir);
combinedOutput.append(gradleOutput).append("\n");
return combinedOutput.toString();
}
}
some python examples
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
corpus = [
“The first document is about space exploration.”,
“The second document is about machine learning.”,
“The third is about gardening.”
]
vectorizer = TfidfVectorizer(stop_words=’english’)
tfidf_matrix = vectorizer.fit_transform(corpus)
def answer_question(query):
query_vector = vectorizer.transform([query])
similarities = cosine_similarity(query_vector, tfidf_matrix)[0]
most_similar_doc_idx = similarities.argmax()
print(“Most relevant document:”, corpus[most_similar_doc_idx])
question = “What is machine learning?”
answer_question(question)
AI Agentic LLM tasks
Anon and deanon examples
AnonymizerRefined:
from functools import wraps
import re
from faker import Faker
import spacy
from DeanonymizerRefined import DeanonymizerRefined
from datetime import datetime
class AnonymizerRefined:
def init(self, custom_patterns=None):
self.fake = Faker()
# Define default regex patterns
phone_pattern = r"\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}" # noqa
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
credit_card_pattern = r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}'
address_pattern = r'\d{1,5}\s\w+(\s\w+)*,\s\w+,\s\w+(\s\w+)*'
# Initialize pattern functions
self.pattern_functions = [
self.create_anonymize_function(phone_pattern,
self.fake.phone_number),
self.create_anonymize_function(email_pattern,
self.fake.email),
self.create_anonymize_function(credit_card_pattern,
self.fake.credit_card_number),
self.create_anonymize_function(address_pattern,
self.fake.address),
]
# Add any custom patterns
if custom_patterns:
for pattern, func in custom_patterns.items():
self.pattern_functions.append(
self.create_anonymize_function(pattern, func))
def generate_unique_fake(self, original, generator_func):
fake_value = generator_func()
while fake_value == original:
fake_value = generator_func()
return fake_value
def create_anonymize_function(self, pattern, fake_func):
try:
re.compile(pattern)
except re.error:
raise ValueError(f"Invalid pattern: {pattern}. Must be a regular expression.") # noqa
def anonymize_func(sentence, anon_sentence, mappings):
data_map = {}
for data in re.findall(pattern, sentence):
# If data is a tuple, join it into a string
if isinstance(data, tuple):
data = ' '.join(data)
fake_data = self.generate_unique_fake(data, fake_func)
data_map[data] = fake_data
anon_sentence = anon_sentence.replace(data, fake_data)
mappings[pattern] = data_map
return anon_sentence
return anonymize_func
def anonymize_data(self, sentence):
anon_sentence = sentence
mappings = {}
for pattern_function in self.pattern_functions:
anon_sentence = pattern_function(sentence, anon_sentence, mappings)
return anon_sentence, mappings
def anonymize(self, *args_to_anonymize):
def inner_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for arg_name in args_to_anonymize:
if arg_name in kwargs:
anonymized_data, _ = self.anonymize_data(
kwargs[arg_name])
kwargs[arg_name] = anonymized_data
return func(*args, **kwargs)
return wrapper
return inner_decorator
Create an instance of the AnonymizerRefined class
anonymizer = AnonymizerRefined()
Create an instance of the DeanonymizerRefined class
deanonymizer = DeanonymizerRefined()
Open the text file
with open(‘mydata.txt’, ‘r’) as file:
# Read the content of the file
content = file.read()
# Anonymize the content
anonymized_content, _ = anonymizer.anonymize_data(content)
Anonymized content and mappings
anonymized_content, mappings = anonymizer.anonymize_data(content)
print(‘ ###################### anonymized_content ###################### ‘)
print(anonymized_content)
print(‘######### mapping ##########’)
print(mappings)
Deanonymize the content
deanonymized_content = deanonymizer.deanonymize(anonymized_content, mappings)
print(‘ ###################### deanonymized_content ###################### ‘)
Print the deanonymized content
print(deanonymized_content)
Get the current date and time
now = datetime.now()
Format the date and time
timestamp = now.strftime(“%Y-%m-%d %H:%M:%S”)
Open the output file in append mode
with open(‘output.txt’, ‘a’) as file:
# Write the timestamp, anonymized content, mappings, and deanonymized content to the file
file.write(“\n”)
file.write(f” ############### ############### ############### ############### Timestamp: {timestamp}\n”)
file.write(” ############### ############### ############### ############### Anonymized content:\n”)
file.write(anonymized_content + “\n”)
file.write(“\n”)
file.write(” ############### ############### ############### ############### Mappings:\n”)
file.write(str(mappings) + “\n”)
file.write(“\n”)
file.write(” ############### ############### ############### ############### Deanonymized content:\n”)
file.write(deanonymized_content + “\n”)
file.write(“\n”)
file.write(“\n”)
DeanonymizerRefined:
class DeanonymizerRefined:
def deanonymize(self, text, mappings):
# Loop through each pattern mapping and replace the anonymized values
# back to the original ones
for _, pattern_map in mappings.items():
for original_value, fake_value in pattern_map.items():
text = text.replace(fake_value, original_value)
return text
chainlet chatbot
# python -m chainlet run ui.py
# python -m chainlet run ui.py --debug
# python -m chainlet run ui.py --debug --verbose
# python -m chainlet run ui.py --debug --verbose --port 8000
# python -m chainlet run ui.py --debug --verbose --port 8000 --host
import os
import sys
from llama_index.core.tools import FunctionTool
from llama_index.core.agent import ReActAgent
from llama_index.llms.ollama import Ollama
#from llama_index.llms.core import Settings
# from llama_index.indices.service_context import ServiceContext
import nest_asyncio
import chainlet as cl
# from llama_index.llms import Ollama
nest_asyncio.apply()
llm = Ollama(model="llama3", request_timeout=120.0)
# Settings.llm = llm
# service_context = ServiceContext.from_defaults(
# llm=Ollama(temperature=0.7, max_tokens=1024)
# )
# llama_index.set_global_default(
# llm=Ollama(model="llama3"),
# chunk_size=512,
# )
# 2. Initialize LLM with the ServiceContext
# llm = Ollama(service_context=service_context)
# 1. create custom tools
def multiply(a: int, b: int) -> int:
"""Multiply two numbers together."""
return a * b
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
def subtract(a: int, b: int) -> int:
"""Subtract two numbers together."""
return a - b
def divide(a: int, b: int) -> int:
"""Divide two numbers together."""
return a / b
multiply_tool = FunctionTool.from_defaults(fn=multiply)
add_tool = FunctionTool.from_defaults(fn=add)
subtract_tool = FunctionTool.from_defaults(fn=subtract)
divide_tool = FunctionTool.from_defaults(fn=divide)
agent = ReActAgent.from_tools([multiply_tool, add_tool, subtract_tool, divide_tool], llm = llm, verbose = True,)
# 2. create a custom agent
@cl.on_chat_start
async def on_chat_start():
await cl.Message(content="Hello! I am a simple calculator bot. Please enter the first number.")
cl.user_session.set("agent", agent)
@cl.on_message
async def on_message(message: cl.Message):
agent = cl.user_session.get("agent")
response = agent.chat(message.content)
await cl.Message(content=str(response)).send()