date_collected
stringclasses
1 value
repo_name
stringlengths
6
116
file_name
stringlengths
2
220
file_contents
stringlengths
13
357k
prompts
sequence
2024-01-10
ezsinehan/speakers-third-eye
backend~gettingResponses~gptresponse.py
import openai import json # Set your OpenAI API key here openai.api_key = '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' # Read the dataset from the JSON file with open('/Users/sinehanezhilmuthu/Desktop/csShit/stev2/backend/gettingData/parsingPredictions/parsed_data.json', 'r') as file: dataset = json.load(file) # Convert the dataset to a string dataset_str = json.dumps(dataset) # Create a GPT-3 prompt to generate recommendations based on the dataset prompt = f"Based on the provided dataset:\n{dataset_str}\n\nPlease provide specific recommendations related to the audiences emotions to the speaker whilist citing to parts in their speech using quotes, I want at least one quote and give a better example on how they could rephrase their speech, on how to increase positive emotions like interest and reduce negative emotions like confusion. Note that the text in the dataset is the speaker's speech. Only one reccomendation per run is needed, but go in detail." # Generate a response from GPT-3 response = openai.Completion.create( engine="text-davinci-002", prompt=prompt, max_tokens=500 ) # Extract the generated recommendations from the response recommendations = response.choices[0].text # Convert the recommendations to a dictionary recommendations_dict = {"recommendations": recommendations} # Save the recommendations as a JSON file with open('recommendations.json', 'w') as output_file: json.dump(recommendations_dict, output_file)
[ "Based on the provided dataset:\nPLACEHOLDER\n\nPlease provide specific recommendations related to the audiences emotions to the speaker whilist citing to parts in their speech using quotes, I want at least one quote and give a better example on how they could rephrase their speech, on how to increase positive emotions like interest and reduce negative emotions like confusion. Note that the text in the dataset is the speaker's speech. Only one reccomendation per run is needed, but go in detail." ]
2024-01-10
daveshap/SynopsisGenerator
finetune.py
import requests import openai from pprint import pprint with open('openaiapikey.txt', 'r') as infile: open_ai_api_key = infile.read() openai.api_key = open_ai_api_key def file_upload(filename, purpose='fine-tune'): resp = openai.File.create(purpose=purpose, file=open(filename)) pprint(resp) return resp def file_list(): resp = openai.File.list() pprint(resp) def finetune_model(fileid, suffix, model='davinci'): header = {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % open_ai_api_key} payload = {'training_file': fileid, 'model': model, 'suffix': suffix} resp = requests.request(method='POST', url='https://api.openai.com/v1/fine-tunes', json=payload, headers=header, timeout=45) pprint(resp.json()) def finetune_list(): header = {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % open_ai_api_key} resp = requests.request(method='GET', url='https://api.openai.com/v1/fine-tunes', headers=header, timeout=45) pprint(resp.json()) def finetune_events(ftid): header = {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % open_ai_api_key} resp = requests.request(method='GET', url='https://api.openai.com/v1/fine-tunes/%s/events' % ftid, headers=header, timeout=45) pprint(resp.json()) def finetune_get(ftid): header = {'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % open_ai_api_key} resp = requests.request(method='GET', url='https://api.openai.com/v1/fine-tunes/%s' % ftid, headers=header, timeout=45) pprint(resp.json()) #resp = file_upload('synopsis.jsonl') #finetune_model(resp['id'], 'synopsis', 'davinci') finetune_list() #openai.FineTune.cancel("ft-2ZxHjUVe5DpqK2EsYyA0YtKz")
[]
2024-01-10
geoffreysteven/Project3_Tennis
ddpg_agent.py
import numpy as np import random import copy from collections import namedtuple, deque from model import Actor, Critic import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(1e6) # replay buffer size BATCH_SIZE = 512 # minibatch size GAMMA = 0.99 # discount factor TAU = 1e-3 # for soft update of target parameters LR_ACTOR = 1e-3 # learning rate of the actor LR_CRITIC = 1e-3 # learning rate of the critic WEIGHT_DECAY = 0.0 # L2 weight decay device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Agent(): """Interacts with and learns from the environment.""" def __init__(self, state_size, action_size, random_seed): """Initialize an Agent object. Params ====== state_size (int): dimension of each state action_size (int): dimension of each action random_seed (int): random seed """ self.state_size = state_size self.action_size = action_size self.seed = random.seed(random_seed) # Actor Network (w/ Target Network) self.actor_local = Actor(state_size, action_size, random_seed).to(device) self.actor_target = Actor(state_size, action_size, random_seed).to(device) self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR) # Critic Network (w/ Target Network) self.critic_local = Critic(state_size, action_size, random_seed).to(device) self.critic_target = Critic(state_size, action_size, random_seed).to(device) self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY) # Noise process self.noise = OUNoise(action_size, random_seed) # Replay memory self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed) def step(self, state, action, reward, next_state, done): """Save experience in replay memory, and use random sample from buffer to learn.""" # Save experience / reward self.memory.add(state, action, reward, next_state, done) def learn_batch(self): # Learn, if enough samples are available in memory if len(self.memory) > BATCH_SIZE: experiences = self.memory.sample() self.learn(experiences, GAMMA) def act(self, state, add_noise=True): """Returns actions for given state as per current policy.""" state = torch.from_numpy(state).float().to(device) self.actor_local.eval() with torch.no_grad(): action = self.actor_local(state).cpu().data.numpy() self.actor_local.train() if add_noise: action += self.noise.sample() return np.clip(action, -1, 1) def reset(self): self.noise.reset() def learn(self, experiences, gamma): """Update policy and value parameters using given batch of experience tuples. Q_targets = r + γ * critic_target(next_state, actor_target(next_state)) where: actor_target(state) -> action critic_target(state, action) -> Q-value Params ====== experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples gamma (float): discount factor """ states, actions, rewards, next_states, dones = experiences # ---------------------------- update critic ---------------------------- # # Get predicted next-state actions and Q values from target models actions_next = self.actor_target(next_states) Q_targets_next = self.critic_target(next_states, actions_next) # Compute Q targets for current states (y_i) Q_targets = rewards + (gamma * Q_targets_next * (1 - dones)) # Compute critic loss Q_expected = self.critic_local(states, actions) critic_loss = F.mse_loss(Q_expected, Q_targets) # Minimize the loss self.critic_optimizer.zero_grad() critic_loss.backward() # as per class benchmark implementation Attempt #3 torch.nn.utils.clip_grad_norm(self.critic_local.parameters(), 1) self.critic_optimizer.step() # ---------------------------- update actor ---------------------------- # # Compute actor loss actions_pred = self.actor_local(states) actor_loss = -self.critic_local(states, actions_pred).mean() # Minimize the loss self.actor_optimizer.zero_grad() actor_loss.backward() self.actor_optimizer.step() # ----------------------- update target networks ----------------------- # self.soft_update(self.critic_local, self.critic_target, TAU) self.soft_update(self.actor_local, self.actor_target, TAU) def soft_update(self, local_model, target_model, tau): """Soft update model parameters. θ_target = τ*θ_local + (1 - τ)*θ_target Params ====== local_model: PyTorch model (weights will be copied from) target_model: PyTorch model (weights will be copied to) tau (float): interpolation parameter """ for target_param, local_param in zip(target_model.parameters(), local_model.parameters()): target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data) class OUNoise: """Ornstein-Uhlenbeck process.""" def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2): """Initialize parameters and noise process.""" self.mu = mu * np.ones(size) self.theta = theta self.sigma = sigma self.dt = 1e-2 self.seed = random.seed(seed) self.reset() def reset(self): """Reset the internal state (= noise) to mean (mu).""" self.state = copy.copy(self.mu) def sample(self): # based on brownian motion as per class code sample """Update internal state and return it as a noise sample.""" x = self.state #### - Old code from DDPG Pendulum # dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))]) ### - Revised OUNoise from OpenAI Noise Blog/Paper # replace with AI Gym's https://github.com/openai/baselines/blob/master/baselines/ddpg/noise.py: # x = self.x_prev + self.theta * (self.mu - self.x_prev) * self.dt + self.sigma * np.sqrt(self.dt) * np.random.normal(size=self.mu.shape) dx = self.theta * (self.mu - x) * self.dt + self.sigma * np.sqrt(self.dt) * np.array([np.random.normal() for i in range(len(x))]) self.state = x + dx return self.state # def sample(self): # normal gaussian noise # """Update internal state and return it as a noise sample.""" # x = self.state # dx = return np.random.normal(self.mu, self.sigma) # self.state = x + dx # return self.state # OrnsteinUhlenbeckActionNoise is from OpenAI's blog on noise: # https://github.com/openai/baselines/blob/master/baselines/ddpg/noise.py # The noise code below is from OpenAI's blog, copied here for reference # class ActionNoise(object): # def reset(self): # pass # # class OrnsteinUhlenbeckActionNoise(ActionNoise): # def __init__(self, mu, sigma, theta=.15, dt=1e-2, x0=None): # self.theta = theta # self.mu = mu # self.sigma = sigma # self.dt = dt # self.x0 = x0 # self.reset() # # def __call__(self): # x = self.x_prev + self.theta * (self.mu - self.x_prev) * self.dt + self.sigma * np.sqrt(self.dt) * np.random.normal(size=self.mu.shape) # self.x_prev = x # return x # # def reset(self): # self.x_prev = self.x0 if self.x0 is not None else np.zeros_like(self.mu) # # def __repr__(self): # return 'OrnsteinUhlenbeckActionNoise(mu={}, sigma={})'.format(self.mu, self.sigma) # AdaptiveParamNoiseSpec is from OpenAI's blog on noise: # https://github.com/openai/baselines/blob/master/baselines/ddpg/noise.py # class AdaptiveParamNoiseSpec(object): # def __init__(self, initial_stddev=0.1, desired_action_stddev=0.1, adoption_coefficient=1.01): # self.initial_stddev = initial_stddev # self.desired_action_stddev = desired_action_stddev # self.adoption_coefficient = adoption_coefficient # # self.current_stddev = initial_stddev # # def adapt(self, distance): # if distance > self.desired_action_stddev: # # Decrease stddev. # self.current_stddev /= self.adoption_coefficient # else: # # Increase stddev. # self.current_stddev *= self.adoption_coefficient # # def get_stats(self): # stats = { # 'param_noise_stddev': self.current_stddev, # } # return stats # # def __repr__(self): # fmt = 'AdaptiveParamNoiseSpec(initial_stddev={}, desired_action_stddev={}, adoption_coefficient={})' # return fmt.format(self.initial_stddev, self.desired_action_stddev, self.adoption_coefficient) # NormalActionNoise is from OpenAI's blog on noise: # https://github.com/openai/baselines/blob/master/baselines/ddpg/noise.py # class NormalActionNoise(ActionNoise): # def __init__(self, mu, sigma): # self.mu = mu # self.sigma = sigma # # def __call__(self): # return np.random.normal(self.mu, self.sigma) # # def __repr__(self): # return 'NormalActionNoise(mu={}, sigma={})'.format(self.mu, self.sigma) # code for replaybufer is from DDPG_Pendulum class repo class ReplayBuffer: """Fixed-size buffer to store experience tuples.""" def __init__(self, action_size, buffer_size, batch_size, seed): """Initialize a ReplayBuffer object. Params ====== buffer_size (int): maximum size of buffer batch_size (int): size of each training batch """ self.action_size = action_size self.memory = deque(maxlen=buffer_size) # internal memory (deque) self.batch_size = batch_size self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"]) self.seed = random.seed(seed) def add(self, state, action, reward, next_state, done): """Add a new experience to memory.""" e = self.experience(state, action, reward, next_state, done) self.memory.append(e) def sample(self): """Randomly sample a batch of experiences from memory.""" experiences = random.sample(self.memory, k=self.batch_size) states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device) actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device) rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device) next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device) dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device) return (states, actions, rewards, next_states, dones) def __len__(self): """Return the current size of internal memory.""" return len(self.memory)
[]
2024-01-10
bigai-nlco/LooGLE
Prediction~pred_llamaindex.py
import os import torch import json import argparse from datasets import load_dataset from llama_index import GPTVectorStoreIndex, Document, ServiceContext from llama_index.indices.prompt_helper import PromptHelper from transformers import AutoTokenizer import openai import tiktoken #import GPUtil stopped_num = 10000000 delay = 10 # Gpus = GPUtil.getGPUs() def get_gpu_info(): gpulist = [] GPUtil.showUtilization() for gpu in Gpus: print('gpu.id:', gpu.id) print('total GPU:', gpu.memoryTotal) print('GPU usage:', gpu.memoryUsed) print('gpu usage percent:', gpu.memoryUtil * 100) gpulist.append([ gpu.id, gpu.memoryTotal, gpu.memoryUsed,gpu.memoryUtil * 100]) return gpulist def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument('--model_name', type=str, default="llama-index", help="raw model name for evaluation") parser.add_argument('--task', type=str, default=None, help="long context understanding tasks in LooGLE", choices=["shortdep_qa","longdep_qa","longdep_summarization","shortdep_cloze"]) parser.add_argument('--max_length', type=int, default=None, help="the max length of input prompt") parser.add_argument('--model_path', type=str, default="./Models/") parser.add_argument('--output_path', type=str, default="./Output/") return parser.parse_args(args) def num_tokens_from_string(string: str, encoding_name: str) -> int: """Returns the number of tokens in a text string.""" encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens def get_pred(data_instance, tokenizer, max_length, max_gen, prompt_format): ans, groundtruth = [], [] preds = {} raw_inputs = data_instance['input'] documents = [Document(text=raw_inputs)] prompt_helper = PromptHelper( context_window=max_length + 1000, num_output=max_gen, chunk_size_limit=1024, chunk_overlap_ratio=0.1, ) service_context = ServiceContext.from_defaults( context_window=max_length + 1000, num_output=max_gen, prompt_helper=prompt_helper, chunk_size_limit=1024, ) index = GPTVectorStoreIndex.from_documents(documents, service_context=service_context) query_engine = index.as_query_engine() if data_instance['qa_pairs'] == 'none': preds['qa_pairs'] = data_instance['qa_pairs'] json_obj = {'input': raw_inputs} prompt = prompt_format.format(**json_obj) tokenized_prompt = tokenizer.encode(prompt) if len(tokenized_prompt) > max_length: half = int(max_length/2) prompt = tokenizer.decode(tokenized_prompt[:half])+tokenizer.decode(tokenized_prompt[-half:]) rsp = query_engine.query(prompt).response ans.append(rsp) groundtruth.append(data_instance["output"]) else: preds['qa_pairs'] = eval(data_instance['qa_pairs']) for j in eval(data_instance['qa_pairs']): json_obj = {'Q':j['Q'], 'input': raw_inputs} prompt = prompt_format.format(**json_obj) tokenized_prompt = tokenizer.encode(prompt) if len(tokenized_prompt) > max_length: half = int(max_length/2) prompt = tokenizer.decode(tokenized_prompt[:half])+tokenizer.decode(tokenized_prompt[-half:]) rsp = query_engine.query(prompt).response ans.append(rsp) groundtruth.append(j['A']) preds['llm_output'] = ans preds['output'] = groundtruth return preds def loads(path, task): data = [] with open(path+task+".jsonl", "r") as f: lines = f.readlines() for line in lines: data.append(json.loads(line)) return data if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args = parse_args() # data = load_dataset('bigainlco/LooGLE', args.task, split="test") data = loads("LooGLE-testdata/", args.task) tokenizer = tiktoken.get_encoding("cl100k_base") task2prompt = json.load(open("./config/task2prompt.json", "r")) task2maxlen = json.load(open("./config/task2maxlen.json", "r")) prompt_format = task2prompt[args.task] max_gen = task2maxlen[args.task] for i in data: predictions = get_pred(i, tokenizer, args.max_length, max_gen, prompt_format) with open(args.output_path + args.task + '_' + args.model_name + ".jsonl", "a+") as g: g.write(json.dumps(predictions)+'\n')
[ "./config/task2prompt.json" ]
2024-01-10
bigai-nlco/LooGLE
Prediction~pred_gpt_models.py
import os import torch import json import argparse from transformers import AutoTokenizer, AutoModelForCausalLM import openai from datasets import load_dataset import tiktoken # import GPUtil stopped_num = 10000000 delay = 10 # Gpus = GPUtil.getGPUs() def get_gpu_info(): gpulist = [] GPUtil.showUtilization() for gpu in Gpus: print('gpu.id:', gpu.id) print('total GPU:', gpu.memoryTotal) print('GPU usage:', gpu.memoryUsed) print('gpu usage percent:', gpu.memoryUtil * 100) gpulist.append([ gpu.id, gpu.memoryTotal, gpu.memoryUsed,gpu.memoryUtil * 100]) return gpulist def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument('--model_name', type=str, default=None, help="raw model name for evaluation", choices=["gpt-3.5-turbo-16k", "gpt-4"]) parser.add_argument('--task', type=str, default=None, help="long context understanding tasks in LooGLE", choices=["shortdep_qa","longdep_qa","longdep_summarization","shortdep_cloze"]) parser.add_argument('--max_length', type=int, default=None, help="the max length of input prompt") parser.add_argument('--model_path', type=str, default="./Models/") parser.add_argument('--output_path', type=str, default="./Output/") return parser.parse_args(args) def num_tokens_from_string(string: str, encoding_name: str) -> int: """Returns the number of tokens in a text string.""" encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens def get_pred(model, data_instance, tokenizer, max_length, max_gen, prompt_format): ans, groundtruth = [], [] preds = {} raw_inputs = data_instance['input'] if data_instance['qa_pairs'] == 'none': preds['qa_pairs'] = data_instance['qa_pairs'] json_obj = {'input': raw_inputs} prompt = prompt_format.format(**json_obj) tokenized_prompt = tokenizer.encode(prompt) if len(tokenized_prompt) > max_length: half = int(max_length/2) prompt = tokenizer.decode(tokenized_prompt[:half]) + tokenizer.decode(tokenized_prompt[-half:]) rsp = openai.ChatCompletion.create( model = model, messages = [{"role": "system", "content":prompt}], temperature = 0.0, top_p = 1, max_tokens = max_gen, frequency_penalty = 0, presence_penalty = 0 ) pred = rsp['choices'][0]['message']['content'] ans.append(pred) groundtruth.append(raw_inputs) else: preds['qa_pairs'] = eval(data_instance['qa_pairs']) for j in eval(data_instance['qa_pairs']): json_obj = {'Q':j['Q'], 'input': raw_inputs} prompt = prompt_format.format(**json_obj) tokenized_prompt = tokenizer.encode(prompt) if len(tokenized_prompt) > max_length: half = int(max_length/2) prompt = tokenizer.decode(tokenized_prompt[:half])+tokenizer.decode(tokenized_prompt[-half:]) rsp = openai.ChatCompletion.create( model = model, messages = [{"role": "system", "content":prompt}], temperature = 0.0, top_p = 1, max_tokens = max_gen, frequency_penalty = 0, presence_penalty = 0 ) pred = rsp['choices'][0]['message']['content'] ans.append(pred) groundtruth.append(j['A']) preds['llm_output'] = ans preds['output'] = groundtruth return preds # def loads(path, task): # data = [] # with open(path+task+".jsonl", "r") as f: # lines = f.readlines() # for line in lines: # data.append(json.loads(line)) # return data if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') args = parse_args() data = load_dataset('bigainlco/LooGLE', args.task, split="test") #data = loads("LooGLE-testdata/", args.task) tokenizer = tiktoken.get_encoding("cl100k_base") task2prompt = json.load(open("./config/task2prompt.json", "r")) task2maxlen = json.load(open("./config/task2maxlen.json", "r")) prompt_format = task2prompt[args.task] max_gen = task2maxlen[args.task] for i in data: predictions = get_pred(args.model_name, i, tokenizer, args.max_length, max_gen, prompt_format) with open(args.output_path + args.task + '_' + args.model_name+".jsonl", "a+") as g: g.write(json.dumps(predictions)+'\n')
[ "./config/task2prompt.json" ]
2024-01-10
bigai-nlco/LooGLE
Evaluation~llm_eval.py
import json from nltk.translate.bleu_score import sentence_bleu from nltk.translate.meteor_score import single_meteor_score from rouge import Rouge from bert_score import score import numpy as np import argparse import openai, os from llm_score import ( get_gpt4_score ) def evaluation(data, scores, functions, task): for i in range(len(data["output"])): hyp, ref = data["llm_output"][i], data["output"][i] if "qa_pairs" in data and data["qa_pairs"] != "none": question = data["qa_pairs"][i]["Q"] else: question = "" for j in functions: if j not in scores: scores[j] = [] scores[j].append(eval(j)(question, ref, hyp, task)) return scores def get_accuracy(result, functions, task): final_score = {} for i in functions: res = result[i] if "qa" in task: final_score[i] = res.count("True") / (res.count("True") + res.count("False")) else: final_score[i] = np.mean(res) return final_score def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default=None, help="model name for evaluation" ) parser.add_argument( "--task", type=str, default=None, help="long context understanding tasks in LooGLE", choices=[ "shortdep_qa", "longdep_qa", "longdep_summarization", ], ) parser.add_argument("--output_path", type=str, default="./Output/") parser.add_argument( "--eval_metric", type=str, default="llm", help="evaluation method for LLM predictions", choices=["llm"], ) return parser.parse_args(args) if __name__ == "__main__": args = parse_args() openai_api_key = os.environ["OPENAI_API_KEY"] eval_functions = ["get_gpt4_score"] score_result = {} with open( args.output_path + args.task + "_" + args.model_name + ".jsonl", "r" ) as f: for line in f.readlines(): ds_llm = json.loads(line) score_result = evaluation(ds_llm, score_result, eval_functions, args.task) print(get_accuracy(score_result, eval_functions, args.task))
[]
2024-01-10
bigai-nlco/LooGLE
Evaluation~llm_score.py
import json import numpy as np import openai def get_gpt4_score(question, reference, hypothesis, task): if "qa" in task: p = "Given one question, there is a groundtruth and a predict_answer. Please decide whether they are the same or not in semantic. Please only output 'True' or 'False' ." prompt = [{"role": "system", "content": p,}, { "role": "user", "content": "Question: " + question + "\n" + "groudtruth = " + reference + "\n" + "predict_answer = " + hypothesis, }] else: # p = "There is a groundtruth summary of a arxiv paper and a auto-generated summary .Please Compare generated summary with the goundtruth and evaluate the generated summary from the perspectives of information completeness, consistency, fluency, and grammar by giving a score within the range of 0 to 100." prompt_format = "There is a groundtruth summary of a arxiv paper and a auto-generated summary .Please Compare generated summary with the goundtruth and evaluate the generated summary from the perspectives of information completeness, consistency, fluency, and grammar by giving a score within the range of 0 to 100. \nGroundtruth = {} \nGenerated = {} \nScore = " prompt = prompt_format.format(reference, hypothesis) prompt = [{"role": "system", "content": prompt}] rr = openai.ChatCompletion.create( model="gpt-4", messages=prompt, temperature=0.0, top_p=1, max_tokens=10, frequency_penalty=0, presence_penalty=0, ) rsp = rr["choices"][0]["message"]["content"] if "qa" in task: return rsp else: return int(rsp)
[ "\n", "There is a groundtruth summary of a arxiv paper and a auto-generated summary .Please Compare generated summary with the goundtruth and evaluate the generated summary from the perspectives of information completeness, consistency, fluency, and grammar by giving a score within the range of 0 to 100. \nGroundtruth = {} \nGenerated = {} \nScore = ", "Given one question, there is a groundtruth and a predict_answer. Please decide whether they are the same or not in semantic. Please only output 'True' or 'False' .", "predict_answer = ", "There is a groundtruth summary of a arxiv paper and a auto-generated summary .Please Compare generated summary with the goundtruth and evaluate the generated summary from the perspectives of information completeness, consistency, fluency, and grammar by giving a score within the range of 0 to 100. \nGroundtruth = PLACEHOLDER \nGenerated = PLACEHOLDER \nScore = " ]
2024-01-10
bigai-nlco/LooGLE
Evaluation~automatic_eval.py
import json import openai from nltk.translate.bleu_score import sentence_bleu from nltk.translate.meteor_score import single_meteor_score from rouge import Rouge from bert_score import score import numpy as np import argparse import openai from automatic_metrics import ( get_bleu_score, get_rouge_score, get_meteor_score, get_bertscore, get_exact_match, get_partial_match ) def evaluation(data, scores, functions, task): for i in range(len(data["output"])): hyp, ref = data["llm_output"][i], data["output"][i] if hyp == '': hyp = 'None' if "qa_pairs" in data: if data["qa_pairs"] != "none": question = data["qa_pairs"][i]["Q"] else: question = "" for j in functions: if j not in scores: scores[j] = [] scores[j].append(eval(j)(question, ref, hyp, task)) return scores def get_semantic_matching(result, functions): final_score = {} for i in functions: if type(result[i][0]) is tuple: l = result[i] final_score[i] = [np.mean([i[j] for i in l]) for j in range(len(l[0]))] else: final_score[i] = np.mean(result[i]) return final_score def get_match_score(result, functions): final_score = {} for i in functions: match_count = np.sum([j[0] for j in result[i]]) all_count = np.sum([j[1] for j in result[i]]) final_score[i] = round(match_count / all_count, 4) return final_score def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default=None, help="model name for evaluation" ) parser.add_argument( "--task", type=str, default=None, help="long context understanding tasks in LooGLE", choices=[ "shortdep_qa", "shortdep_cloze", "longdep_qa", "longdep_summarization", ], ) parser.add_argument("--output_path", type=str, default="./Output/") parser.add_argument( "--eval_metric", type=str, default=None, help="evaluation method for LLM predictions", choices=["automatic_sim", "automatic_match"], ) return parser.parse_args(args) if __name__ == "__main__": args = parse_args() if args.eval_metric == "automatic_sim": eval_functions = [ "get_bleu_score", "get_rouge_score", "get_meteor_score", "get_bertscore" ] elif args.eval_metric == "automatic_match": eval_functions = ["get_exact_match", "get_partial_match"] score_result = {} with open( args.output_path + args.task + "_" + args.model_name + ".jsonl", "r" ) as f: for line in f.readlines(): ds_llm = json.loads(line) score_result = evaluation(ds_llm, score_result, eval_functions, args.task) if args.eval_metric == "automatic_sim": print(get_semantic_matching(score_result, eval_functions)) elif args.eval_metric == "automatic_match": print(get_match_score(score_result, eval_functions))
[]
2024-01-10
bigai-nlco/LooGLE
Retrieval~pred_retrieval_based_method.py
import os from typing import Any import torch import json import argparse import openai from datasets import load_dataset from transformers import AutoTokenizer, AutoModelForCausalLM from llama_index import GPTVectorStoreIndex, Document, ServiceContext from langchain.embeddings.huggingface import HuggingFaceEmbeddings from llama_index.indices.prompt_helper import PromptHelper from llama_index.llms import ( OpenAI, CustomLLM, HuggingFaceLLM, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.llms.base import llm_completion_callback import tiktoken class OpenSourceLLM(CustomLLM): num_output: int = 0 model_name: str = "" max_length: int = 0 tokenizer: AutoTokenizer = None model: AutoModelForCausalLM = None def __init__(self, num_output, max_length, model_path, model_name) -> None: super().__init__() self.num_output = num_output self.model_name = model_name self.max_length = max_length self.tokenizer = AutoTokenizer.from_pretrained( os.path.join(model_path, model_name), trust_remote_code=True ) self.model = AutoModelForCausalLM.from_pretrained( os.path.join(model_path, model_name), trust_remote_code=True, torch_dtype=torch.bfloat16 ).to(device) self.model.eval() @property def metadata(self) -> LLMMetadata: """Get LLM metadata.""" return LLMMetadata( context_window=self.max_length, num_output=self.num_output, model_name=self.model_name, ) @llm_completion_callback() def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: print("input:", prompt) input_ids = self.tokenizer( prompt, truncation=False, return_tensors="pt" ).input_ids input_ids = input_ids.to("cuda") context_length = input_ids.shape[-1] with torch.no_grad(): output = self.model.generate( input_ids, max_new_tokens=self.num_output, temperature=1.0, num_beams=1, do_sample=False, repetition_penalty=float(2), )[0] text = self.tokenizer.decode( output[context_length:], skip_special_tokens=True) return CompletionResponse(text=text) @llm_completion_callback() def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen: raise NotImplementedError() def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default="llama-index", help="raw model name for evaluation", ) parser.add_argument( "--emb_model_name", type=str, default="", help="embedding_model" ) parser.add_argument( "--task", type=str, default=None, help="long context understanding tasks in LooGLE", choices=[ "shortdep_qa", "longdep_qa", "longdep_summarization", "shortdep_cloze", ], ) parser.add_argument( "--max_length", type=int, default=None, help="the max length of input prompt" ) parser.add_argument("--model_path", type=str, default="./Models/") parser.add_argument("--output_path", type=str, default="./Output/") return parser.parse_args(args) def num_tokens_from_string(string: str, encoding_name: str) -> int: """Returns the number of tokens in a text string.""" encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens def get_pred(data_instance, service_context): ans, groundtruth = [], [] preds = {} preds["qa_pairs"] = eval(data_instance["qa_pairs"]) documents = [Document(text=data_instance["input"])] index = GPTVectorStoreIndex.from_documents( documents, service_context=service_context ) query_engine = index.as_query_engine() for j in eval(data_instance["qa_pairs"]): rsp = query_engine.query( "Question: " + j["Q"] + "\n" + "Answer: ").response ans.append(rsp) groundtruth.append(j["A"]) preds["llm_output"] = ans preds["output"] = groundtruth return preds def loads(path, task): data = [] with open(path+task+".jsonl", "r") as f: lines = f.readlines() for line in lines: data.append(json.loads(line)) return data if __name__ == "__main__": open_source_model = [ "rwkv-4-14b-pile", "long_llama_3b", "LLaMA-2-7B-32K", "chatglm2-6b-32k", ] openai_model = ["gpt-3.5-turbo-16k", "gpt-4"] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") args = parse_args() task2maxlen = json.load(open("./config/task2maxlen.json", "r")) max_gen = task2maxlen[args.task] # data = load_dataset("bigainlco/LooGLE", args.task, split="test") data = loads("LooGLE-testdata/", args.task) if args.model_name in open_source_model: llm = OpenSourceLLM(max_gen, args.max_length, args.model_path, args.model_name) elif args.model_name in openai_model: llm = OpenAI(model=args.model_name) else: raise NameError("model name not found!") embed_model = HuggingFaceEmbeddings(model_name=args.emb_model_name) prompt_helper = PromptHelper( context_window=args.max_length, num_output=max_gen, chunk_size_limit=1024, chunk_overlap_ratio=0.1, ) service_context = ServiceContext.from_defaults( llm=llm, context_window=args.max_length, num_output=max_gen, embed_model=embed_model, prompt_helper=prompt_helper, chunk_size_limit=1024, ) for i in data: predictions = get_pred(i, service_context) with open( args.output_path + args.task + "_" + args.model_name + ".jsonl", "a+" ) as g: g.write(json.dumps(predictions) + "\n")
[]
2024-01-10
colindecourt/record
utils~carrada_functions.py
""" From https://github.com/valeoai/MVRSS """ import json import numpy as np import torch import torch.nn as nn import os from datasets.carrada.dataloaders import Rescale, Flip, HFlip, VFlip from utils.loss import CoherenceLoss, SoftDiceLoss def get_class_weights(signal_type, weight_path): """Load class weights for custom loss @param signal_type: 'range_doppler' or 'range_angle' @param weight_path: path to class weights @return: class weights """ if signal_type == 'range_angle': file_name = 'ra_weights.json' elif signal_type == 'range_doppler': file_name = 'rd_weights.json' else: raise ValueError('Signal type {} is not supported.'.format(signal_type)) file_path = os.path.join(weight_path, file_name) with open(file_path, 'r') as fp: weights = json.load(fp) weights = np.array([weights['background'], weights['pedestrian'], weights['cyclist'], weights['car']]) weights = torch.from_numpy(weights) return weights def normalize(data, signal_type, proj_path, norm_type='local'): """ Method to normalise the radar views @param data: radar view @param signal_type: signal to normalise ('range_doppler', 'range_angle' and 'angle_doppler') @param proj_path: path to the project to load weights @param norm_type: type of normalisation to apply ('local' or 'tvt') @return: normalised data """ if norm_type in ('local'): min_value = torch.min(data) max_value = torch.max(data) norm_data = torch.div(torch.sub(data, min_value), torch.sub(max_value, min_value)) return norm_data elif signal_type == 'range_doppler': if norm_type == 'tvt': file_path = os.path.join(proj_path, 'configs', 'carrada', 'weights_config', 'rd_stats_all.json') else: raise TypeError('Global type {} is not supported'.format(norm_type)) with open(file_path, 'r') as fp: rd_stats = json.load(fp) min_value = torch.tensor(rd_stats['min_val']) max_value = torch.tensor(rd_stats['max_val']) elif signal_type == 'range_angle': if norm_type == 'tvt': file_path = os.path.join(proj_path, 'configs', 'carrada', 'weights_config', 'ra_stats_all.json') else: raise TypeError('Global type {} is not supported'.format(norm_type)) with open(file_path, 'r') as fp: ra_stats = json.load(fp) min_value = torch.tensor(ra_stats['min_val']) max_value = torch.tensor(ra_stats['max_val']) elif signal_type == 'angle_doppler': if norm_type == 'tvt': file_path = os.path.join(proj_path, 'configs', 'carrada', 'weights_config', 'ad_stats_all.json') else: raise TypeError('Global type {} is not supported'.format(norm_type)) with open(file_path, 'r') as fp: ad_stats = json.load(fp) min_value = torch.tensor(ad_stats['min_val']) max_value = torch.tensor(ad_stats['max_val']) else: raise TypeError('Signal {} is not supported.'.format(signal_type)) norm_data = torch.div(torch.sub(data, min_value), torch.sub(max_value, min_value)) return norm_data def get_transformations(transform_names, split='train', sizes=None): """Create a list of functions used for preprocessing @param transform_names: list of str, one for each transformation @param split: split currently used @param sizes: int or tuple (optional) @return: transformations to use for preprocessing (e.g. data augmentation) """ transformations = list() if 'rescale' in transform_names: transformations.append(Rescale(sizes)) if 'flip' in transform_names and split == 'train': transformations.append(Flip(0.5)) if 'vflip' in transform_names and split == 'train': transformations.append(VFlip()) if 'hflip' in transform_names and split == 'train': transformations.append(HFlip()) return transformations def get_metrics(metrics): """Structure the metric results @param metrics: contains statistics recorded during inference @return: metrics values """ metrics_values = dict() acc, acc_by_class = metrics.get_pixel_acc_class() # harmonic_mean=True) prec, prec_by_class = metrics.get_pixel_prec_class() recall, recall_by_class = metrics.get_pixel_recall_class() # harmonic_mean=True) miou, miou_by_class = metrics.get_miou_class() # harmonic_mean=True) dice, dice_by_class = metrics.get_dice_class() metrics_values['acc'] = acc metrics_values['acc_by_class'] = acc_by_class.tolist() metrics_values['prec'] = prec metrics_values['prec_by_class'] = prec_by_class.tolist() metrics_values['recall'] = recall metrics_values['recall_by_class'] = recall_by_class.tolist() metrics_values['miou'] = miou metrics_values['miou_by_class'] = miou_by_class.tolist() metrics_values['dice'] = dice metrics_values['dice_by_class'] = dice_by_class.tolist() return metrics_values
[]
2024-01-10
colindecourt/record
executors~carrada_trainer_sv.py
import imp import os import numpy as np import pytorch_lightning as pl from torch import nn import torch from utils.carrada_functions import get_class_weights, normalize, get_transformations, get_metrics from utils.loss import CoherenceLoss, SoftDiceLoss from evaluation.carrada_metrics import Evaluator class CarradaExecutorSV(pl.LightningModule): def __init__(self, config, model, view='range_doppler'): """ PyTorch lightning base class for training SV-RECORD on CARRADA dataset. @param config: dictionary with training configuration (lr, optimizer, path to data etc.) @param model: instance of the model to train @param view: the view to use (range_angle or range_doppler) """ super(CarradaExecutorSV, self).__init__() self.scheduler = None self.optimizer = None self.model = model self.view = view self.model_cfg = config['model_cfg'] self.dataset_cfg = config['dataset_cfg'] self.train_cfg = config['train_cfg'] weight_path = self.dataset_cfg['weight_path'] self.project_path = self.dataset_cfg['project_path'] self.model_name = self.model_cfg['name'] self.process_signal = self.model_cfg['process_signal'] self.w_size = self.model_cfg['w_size'] self.h_size = self.model_cfg['h_size'] self.nb_classes = self.model_cfg['nb_classes'] self.in_channels = self.model_cfg['in_channels'] self.ckpt_dir = self.train_cfg['ckpt_dir'] self.lr = self.train_cfg['lr'] self.lr_step = self.train_cfg['lr_step'] self.loss_step = self.train_cfg['loss_step'] self.val_step = self.train_cfg['val_step'] self.viz_step = self.train_cfg['viz_step'] self.custom_loss = self.train_cfg['loss'] self.norm_type = self.train_cfg['norm_type'] # Criterion self.criterion = self.define_loss(view, self.custom_loss, weight_path) self.nb_losses = len(self.criterion) # Metrics self.metrics = Evaluator(self.nb_classes) self.save_hyperparameters(config) def define_loss(self, signal_type, custom_loss, weight_path): """ Method to define the loss to use during training @param signal_type: Type of radar view (supported: 'range_doppler', 'range_angle' or 'angle_doppler') @param custom_loss: Short name of the custom loss to use (supported: 'wce', 'sdice', 'wce_w10sdice' or 'wce_w10sdice_w5col') @param weight_path: path to class weights of dataset @return: loss function """ weights = get_class_weights(signal_type, weight_path) if custom_loss == 'wce': loss = nn.CrossEntropyLoss(weight=weights.float()) elif custom_loss == 'sdice': loss = SoftDiceLoss() elif custom_loss == 'wce_w10sdice': ce_loss = nn.CrossEntropyLoss(weight=weights.float()) loss = nn.ModuleList([ce_loss, SoftDiceLoss(global_weight=10.)]) else: loss = nn.CrossEntropyLoss() return loss def configure_optimizers(self): """ Define optimizer and scheduler @return: optimizer and scheduler (if not None) """ self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr) self.scheduler = { 'scheduler': torch.optim.lr_scheduler.ExponentialLR(self.optimizer, gamma=0.9), 'interval': 'epoch', 'frequency': 20 } return [self.optimizer], [self.scheduler] def on_train_start(self): self.logger.log_hyperparams(self.hparams, {"hp/val_global_prec": 0, "hp/val_global_dice": 0, "hp/test_miou": 0, "hp/test_dice": 0, "hp/val_loss": 0, "hp/train_loss": 0, }) def forward(self, x): """ Pytorch Lightning forward pass (inference) @param x: input tensor @return: segmentation mask """ outputs = self.model(x) return outputs def training_step(self, batch, batch_id): """ Perform one training step (forward + backward) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch @return: loss value to log """ if self.view == 'range_doppler': data = batch['rd_matrix'].float() mask = batch['rd_mask'].float() elif self.view == 'range_angle': data = batch['ra_matrix'].float() mask = batch['ra_mask'].float() data = normalize(data, self.view, norm_type=self.norm_type, proj_path=self.project_path) # Forward outputs = self.model(data) # Case without the CoL losses = [c(outputs, torch.argmax(mask, axis=1)) for c in self.criterion] loss = torch.mean(torch.stack(losses)) # Log losses loss_dict = { 'train/loss': loss, 'train/ce': losses[0], 'train/dice': losses[1], } self.log_dict(loss_dict, prog_bar=False, on_step=True, on_epoch=True, logger=True) self.log('hp/train_loss', loss, on_step=False, on_epoch=True, prog_bar=False, logger=True) return loss def on_validation_epoch_end(self): test_results = get_metrics(self.metrics) if self.view == 'range_doppler': test_results_log = { 'val_metrics/rd_acc': test_results['acc'], 'val_metrics/rd_prec': test_results['prec'], 'val_metrics/rd_miou': test_results['miou'], 'val_metrics/rd_dice': test_results['dice'] } elif self.view == 'range_angle': test_results_log = { 'val_metrics/ra_acc': test_results['acc'], 'val_metrics/ra_prec': test_results['prec'], 'val_metrics/ra_miou': test_results['miou'], 'val_metrics/ra_dice': test_results['dice'] } self.log(test_results_log) self.log("hp/val_global_prec", test_results['prec'], on_epoch=True) self.log("hp/val_global_dice", test_results['dice'], on_epoch=True) self.metrics.reset() def validation_step(self, batch, batch_id): """ Perform a validation step (forward pass) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch """ if self.view == 'range_doppler': data = batch['rd_matrix'].float() mask = batch['rd_mask'].float() elif self.view == 'range_angle': data = batch['ra_matrix'].float() mask = batch['ra_mask'].float() data = normalize(data, self.view, norm_type=self.norm_type, proj_path=self.project_path) outputs = self.forward(data) # Compute loss # Case without the CoL losses = [c(outputs, torch.argmax(mask, axis=1)) for c in self.criterion] loss = torch.mean(torch.stack(losses)) # Log losses loss_dict = { 'val/loss': loss, 'val/ce': losses[0], 'val/dice': losses[1], } # Compute metrics self.metrics.add_batch(torch.argmax(mask, axis=1).cpu(), torch.argmax(outputs, axis=1).cpu()) self.log_dict(loss_dict, prog_bar=False, on_step=False, on_epoch=True, logger=True) self.log('hp/val_loss', loss, on_epoch=True) def test_step(self, batch, batch_id): """ Perform a test step (forward pass + evaluation) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch """ if self.view == 'range_doppler': data = batch['rd_matrix'].float() mask = batch['rd_mask'].float() elif self.view == 'range_angle': data = batch['ra_matrix'].float() mask = batch['ra_mask'].float() data = normalize(data, self.view, norm_type=self.norm_type, proj_path=self.project_path) outputs = self.forward(data) # Compute metrics self.metrics.add_batch(torch.argmax(mask, axis=1).cpu(), torch.argmax(outputs, axis=1).cpu()) def on_test_epoch_end(self): """ Compute metrics and log it """ test_results = get_metrics(self.metrics) if self.view == 'range_doppler': test_results_log = { 'test_metrics/rd_acc': test_results['acc'], 'test_metrics/rd_prec': test_results['prec'], 'test_metrics/rd_miou': test_results['miou'], 'test_metrics/rd_dice': test_results['dice'], 'test_metrics/rd_dice_bkg': test_results['dice_by_class'][0], 'test_metrics/rd_dice_ped': test_results['dice_by_class'][1], 'test_metrics/rd_dice_cycl': test_results['dice_by_class'][2], 'test_metrics/rd_dice_car': test_results['dice_by_class'][3], 'test_metrics/rd_iou_bkg': test_results['miou_by_class'][0], 'test_metrics/rd_iou_ped': test_results['miou_by_class'][1], 'test_metrics/rd_iou_cycl': test_results['miou_by_class'][2], 'test_metrics/rd_iou_car': test_results['miou_by_class'][3], } elif self.view == 'range_angle': test_results_log = { 'test_metrics/ra_acc': test_results['acc'], 'test_metrics/ra_prec': test_results['prec'], 'test_metrics/ra_miou': test_results['miou'], 'test_metrics/ra_dice': test_results['dice'], 'test_metrics/ra_dice_bkg': test_results['dice_by_class'][0], 'test_metrics/ra_dice_ped': test_results['dice_by_class'][1], 'test_metrics/ra_dice_cycl': test_results['dice_by_class'][2], 'test_metrics/ra_dice_car': test_results['dice_by_class'][3], 'test_metrics/ra_iou_bkg': test_results['miou_by_class'][0], 'test_metrics/ra_iou_ped': test_results['miou_by_class'][1], 'test_metrics/ra_iou_cycl': test_results['miou_by_class'][2], 'test_metrics/ra_iou_car': test_results['miou_by_class'][3], } self.log_dict(test_results_log, on_epoch=True) self.log(name='hp/test_dice', value=test_results['dice'], on_epoch=True) self.log(name="hp/test_miou", value=test_results['miou'], on_epoch=True) self.metrics.reset()
[]
2024-01-10
colindecourt/record
executors~carrada_trainer.py
import imp import os import numpy as np import pytorch_lightning as pl from torch import nn import torch from utils.carrada_functions import get_class_weights, normalize, get_transformations, get_metrics from utils.loss import CoherenceLoss, SoftDiceLoss from evaluation.carrada_metrics import Evaluator class CarradaExecutor(pl.LightningModule): def __init__(self, config, model): """ PyTorch lightning base class for training MV-RECORD on CARRADA dataset. @param config: dictionary with training configuration (lr, optimizer, path to data etc.) @param model: instance of the model to train """ super(CarradaExecutor, self).__init__() self.scheduler = None self.optimizer = None self.model = model self.model_cfg = config['model_cfg'] self.dataset_cfg = config['dataset_cfg'] self.train_cfg = config['train_cfg'] weight_path = self.dataset_cfg['weight_path'] self.project_path = self.dataset_cfg['project_path'] self.model_name = self.model_cfg['name'] self.process_signal = self.model_cfg['process_signal'] self.w_size = self.model_cfg['w_size'] self.h_size = self.model_cfg['h_size'] self.nb_classes = self.model_cfg['nb_classes'] self.in_channels = self.model_cfg['in_channels'] self.ckpt_dir = self.train_cfg['ckpt_dir'] self.lr = self.train_cfg['lr'] self.lr_step = self.train_cfg['lr_step'] self.loss_step = self.train_cfg['loss_step'] self.val_step = self.train_cfg['val_step'] self.viz_step = self.train_cfg['viz_step'] self.custom_loss = self.train_cfg['loss'] self.norm_type = self.train_cfg['norm_type'] # Criterion self.rd_criterion = self.define_loss('range_doppler', self.custom_loss, weight_path) self.ra_criterion = self.define_loss('range_angle', self.custom_loss, weight_path) self.nb_losses = len(self.rd_criterion) # Metrics self.rd_metrics = Evaluator(self.nb_classes) self.ra_metrics = Evaluator(self.nb_classes) self.save_hyperparameters(config) def define_loss(self, signal_type, custom_loss, weight_path): """ Method to define the loss to use during training @param signal_type: Type of radar view (supported: 'range_doppler', 'range_angle' or 'angle_doppler') @param custom_loss: Short name of the custom loss to use (supported: 'wce', 'sdice', 'wce_w10sdice' or 'wce_w10sdice_w5col') @param weight_path: path to class weights of dataset @return: loss function """ weights = get_class_weights(signal_type, weight_path) if custom_loss == 'wce': loss = nn.CrossEntropyLoss(weight=weights.float()) elif custom_loss == 'sdice': loss = SoftDiceLoss() elif custom_loss == 'wce_w10sdice': ce_loss = nn.CrossEntropyLoss(weight=weights.float()) loss = nn.ModuleList([ce_loss, SoftDiceLoss(global_weight=10.)]) else: loss = nn.CrossEntropyLoss() return loss def configure_optimizers(self): self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr) self.scheduler = { 'scheduler': torch.optim.lr_scheduler.ExponentialLR(self.optimizer, gamma=0.9), 'interval': 'epoch', 'frequency': 20 } return [self.optimizer], [self.scheduler] def on_train_start(self): self.logger.log_hyperparams(self.hparams, {"hp/val_global_prec": 0, "hp/val_global_dice": 0, "hp/test_rd_miou": 0, "hp/test_ra_miou": 0, "hp/val_loss": 0, "hp/train_loss": 0, }) def forward(self, rd_data, ra_data, ad_data=None): """ Pytorch Lightning forward pass (inference) @param rd_data: range doppler tensor @param ra_data: range angle tensor @param ad_data: angle doppler tensor @return: range doppler and range angle segmentation masks """ rd_outputs, ra_outputs = self.model(rd_data, ra_data, ad_data) return rd_outputs, ra_outputs def training_step(self, batch, batch_id): """ Perform one training step (forward + backward) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch @return: loss value to log """ rd_data = batch['rd_matrix'].float() ra_data = batch['ra_matrix'].float() ad_data = batch['ad_matrix'].float() rd_mask = batch['rd_mask'].float() ra_mask = batch['ra_mask'].float() rd_data = normalize(rd_data, 'range_doppler', norm_type=self.norm_type, proj_path=self.project_path) ra_data = normalize(ra_data, 'range_angle', norm_type=self.norm_type, proj_path=self.project_path) ad_data = normalize(ad_data, 'angle_doppler', norm_type=self.norm_type, proj_path=self.project_path) # Forward rd_outputs, ra_outputs = self.model(rd_data, ra_data, ad_data) # Compute loss if self.nb_losses < 3: # Case without the CoL rd_losses = [c(rd_outputs, torch.argmax(rd_mask, axis=1)) for c in self.rd_criterion] rd_loss = torch.mean(torch.stack(rd_losses)) ra_losses = [c(ra_outputs, torch.argmax(ra_mask, axis=1)) for c in self.ra_criterion] ra_loss = torch.mean(torch.stack(ra_losses)) loss = torch.mean(rd_loss + ra_loss) else: # Case with the CoL # Select the wCE and wSDice rd_losses = [c(rd_outputs, torch.argmax(rd_mask, axis=1)) for c in self.rd_criterion[:2]] rd_loss = torch.mean(torch.stack(rd_losses)) ra_losses = [c(ra_outputs, torch.argmax(ra_mask, axis=1)) for c in self.ra_criterion[:2]] ra_loss = torch.mean(torch.stack(ra_losses)) # Coherence loss coherence_loss = self.rd_criterion[2](rd_outputs, ra_outputs) loss = torch.mean(rd_loss + ra_loss + coherence_loss) # Log losses if self.nb_losses > 2: loss_dict = { 'train/loss': loss, 'train/rd_global': rd_loss, 'train/rd_ce': rd_losses[0], 'train/rd_Dice': rd_losses[1], 'train/ra_global': ra_loss, 'train/ra_ce': ra_losses[0], 'train/ra_Dice': ra_losses[1], 'train/coherence': coherence_loss } else: loss_dict = { 'train/loss': loss, 'train/rd_global': rd_loss, 'train/rd_ce': rd_losses[0], 'train/rd_Dice': rd_losses[1], 'train/ra_global': ra_loss, 'train/ra_ce': ra_losses[0], 'train/ra_Dice': ra_losses[1] } self.log_dict(loss_dict, prog_bar=False, on_step=True, on_epoch=True, logger=True) self.log('hp/train_loss', loss, on_step=False, on_epoch=True, prog_bar=False, logger=True) return loss def on_validation_epoch_end(self): test_results = dict() test_results['range_doppler'] = get_metrics(self.rd_metrics) test_results['range_angle'] = get_metrics(self.ra_metrics) test_results['global_acc'] = (1/2)*(test_results['range_doppler']['acc']+ test_results['range_angle']['acc']) test_results['global_prec'] = (1/2)*(test_results['range_doppler']['prec']+ test_results['range_angle']['prec']) test_results['global_dice'] = (1/2)*(test_results['range_doppler']['dice']+ test_results['range_angle']['dice']) test_results_log = { 'val_metrics/rd_acc': test_results['range_doppler']['acc'], 'val_metrics/rd_prec': test_results['range_doppler']['prec'], 'val_metrics/rd_miou': test_results['range_doppler']['miou'], 'val_metrics/rd_dice': test_results['range_doppler']['dice'], 'val_metrics/ra_acc': test_results['range_angle']['acc'], 'val_metrics/ra_prec': test_results['range_angle']['prec'], 'val_metrics/ra_miou': test_results['range_angle']['miou'], 'val_metrics/ra_dice': test_results['range_angle']['dice'], 'val_metrics/global_prec': test_results['global_prec'], 'val_metrics/global_acc': test_results['global_acc'], 'val_metrics/global_dice': test_results['global_dice'] } self.log_dict(test_results_log, on_epoch=True) self.log("hp/val_global_prec", test_results['global_prec'], on_epoch=True) self.log("hp/val_global_dice", test_results['global_dice'], on_epoch=True) self.rd_metrics.reset() self.ra_metrics.reset() def validation_step(self, batch, batch_id): """ Perform a validation step (forward pass) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch """ rd_data = batch['rd_matrix'].float() ra_data = batch['ra_matrix'].float() ad_data = batch['ad_matrix'].float() rd_mask = batch['rd_mask'].float() ra_mask = batch['ra_mask'].float() rd_data = normalize(rd_data, 'range_doppler', norm_type=self.norm_type, proj_path=self.project_path) ra_data = normalize(ra_data, 'range_angle', norm_type=self.norm_type, proj_path=self.project_path) ad_data = normalize(ad_data, 'angle_doppler', norm_type=self.norm_type, proj_path=self.project_path) rd_outputs, ra_outputs = self.forward(rd_data, ra_data, ad_data) # Compute loss if self.nb_losses < 3: # Case without the CoL rd_losses = [c(rd_outputs, torch.argmax(rd_mask, axis=1)) for c in self.rd_criterion] rd_loss = torch.mean(torch.stack(rd_losses)) ra_losses = [c(ra_outputs, torch.argmax(ra_mask, axis=1)) for c in self.ra_criterion] ra_loss = torch.mean(torch.stack(ra_losses)) loss = torch.mean(rd_loss + ra_loss) else: # Case with the CoL # Select the wCE and wSDice rd_losses = [c(rd_outputs, torch.argmax(rd_mask, axis=1)) for c in self.rd_criterion[:2]] rd_loss = torch.mean(torch.stack(rd_losses)) ra_losses = [c(ra_outputs, torch.argmax(ra_mask, axis=1)) for c in self.ra_criterion[:2]] ra_loss = torch.mean(torch.stack(ra_losses)) # Coherence loss coherence_loss = self.rd_criterion[2](rd_outputs, ra_outputs) loss = torch.mean(rd_loss + ra_loss + coherence_loss) # Compute metrics self.rd_metrics.add_batch(torch.argmax(rd_mask, axis=1).cpu(), torch.argmax(rd_outputs, axis=1).cpu()) self.ra_metrics.add_batch(torch.argmax(ra_mask, axis=1).cpu(), torch.argmax(ra_outputs, axis=1).cpu()) if self.nb_losses > 2: loss_dict = { 'val/loss': loss, 'val/rd_global': rd_loss, 'val/rd_ce': rd_losses[0], 'val/rd_Dice': rd_losses[1], 'val/ra_global': ra_loss, 'val/ra_ce': ra_losses[0], 'val/ra_Dice': ra_losses[1], 'val/coherence': coherence_loss } else: loss_dict = { 'val/loss': loss, 'val/rd_global': rd_loss, 'val/rd_ce': rd_losses[0], 'val/rd_Dice': rd_losses[1], 'val/ra_global': ra_loss, 'val/ra_ce': ra_losses[0], 'val/ra_Dice': ra_losses[1] } self.log_dict(loss_dict, prog_bar=False, on_step=False, on_epoch=True, logger=True) self.log('hp/val_loss', loss, on_step=False, on_epoch=True, prog_bar=False, logger=True) def test_step(self, batch, batch_id): """ Perform a test step (forward pass) on a batch of data. @param batch: data batch from the dataloader @param batch_id: id of the current batch """ rd_data = batch['rd_matrix'].float() ra_data = batch['ra_matrix'].float() ad_data = batch['ad_matrix'].float() rd_mask = batch['rd_mask'].float() ra_mask = batch['ra_mask'].float() rd_data = normalize(rd_data, 'range_doppler', norm_type=self.norm_type, proj_path=self.project_path) ra_data = normalize(ra_data, 'range_angle', norm_type=self.norm_type, proj_path=self.project_path) ad_data = normalize(ad_data, 'angle_doppler', norm_type=self.norm_type, proj_path=self.project_path) rd_outputs, ra_outputs = self.forward(rd_data, ra_data, ad_data) # Compute metrics self.rd_metrics.add_batch(torch.argmax(rd_mask, axis=1).cpu(), torch.argmax(rd_outputs, axis=1).cpu()) self.ra_metrics.add_batch(torch.argmax(ra_mask, axis=1).cpu(), torch.argmax(ra_outputs, axis=1).cpu()) def on_test_epoch_end(self): """ Compute metrics and log it """ test_results = dict() test_results['range_doppler'] = get_metrics(self.rd_metrics) test_results['range_angle'] = get_metrics(self.ra_metrics) test_results['global_acc'] = (1/2)*(test_results['range_doppler']['acc']+ test_results['range_angle']['acc']) test_results['global_prec'] = (1/2)*(test_results['range_doppler']['prec']+ test_results['range_angle']['prec']) test_results['global_dice'] = (1/2)*(test_results['range_doppler']['dice']+ test_results['range_angle']['dice']) test_results_log = { 'test_metrics/rd_acc': test_results['range_doppler']['acc'], 'test_metrics/rd_prec': test_results['range_doppler']['prec'], 'test_metrics/rd_miou': test_results['range_doppler']['miou'], 'test_metrics/rd_dice': test_results['range_doppler']['dice'], 'test_metrics/ra_acc': test_results['range_angle']['acc'], 'test_metrics/ra_prec': test_results['range_angle']['prec'], 'test_metrics/ra_miou': test_results['range_angle']['miou'], 'test_metrics/ra_dice': test_results['range_angle']['dice'], 'test_metrics/global_prec': test_results['global_prec'], 'test_metrics/global_acc': test_results['global_acc'], 'test_metrics/global_dice': test_results['global_dice'], 'test_metrics/rd_dice_bkg': test_results['range_doppler']['dice_by_class'][0], 'test_metrics/rd_dice_ped': test_results['range_doppler']['dice_by_class'][1], 'test_metrics/rd_dice_cycl': test_results['range_doppler']['dice_by_class'][2], 'test_metrics/rd_dice_car': test_results['range_doppler']['dice_by_class'][3], 'test_metrics/ra_dice_bkg': test_results['range_angle']['dice_by_class'][0], 'test_metrics/ra_dice_ped': test_results['range_angle']['dice_by_class'][1], 'test_metrics/ra_dice_cycl': test_results['range_angle']['dice_by_class'][2], 'test_metrics/ra_dice_car': test_results['range_angle']['dice_by_class'][3], 'test_metrics/rd_iou_bkg': test_results['range_doppler']['miou_by_class'][0], 'test_metrics/rd_iou_ped': test_results['range_doppler']['miou_by_class'][1], 'test_metrics/rd_iou_cycl': test_results['range_doppler']['miou_by_class'][2], 'test_metrics/rd_iou_car': test_results['range_doppler']['miou_by_class'][3], 'test_metrics/ra_iou_bkg': test_results['range_angle']['miou_by_class'][0], 'test_metrics/ra_iou_ped': test_results['range_angle']['miou_by_class'][1], 'test_metrics/ra_iou_cycl': test_results['range_angle']['miou_by_class'][2], 'test_metrics/ra_iou_car': test_results['range_angle']['miou_by_class'][3], } self.log_dict(test_results_log, on_epoch=True) self.log(name='hp/test_rd_miou', value=test_results['range_doppler']['miou'], on_epoch=True) self.log(name="hp/test_ra_miou", value=test_results['range_angle']['miou'], on_epoch=True) self.rd_metrics.reset() self.ra_metrics.reset()
[]
2024-01-10
yasufumi-nakata/scopus_gpt4
dbot.py
from discord.ext import commands import os import requests import openai import random import discord import asyncio import datetime import pytz import functools import typing TOKEN = "" openai.api_key = "" ELSEVIER_API_KEY = "" # CHANNEL_ID = int(os.getenv('CHANNEL_ID3')) HEADERS = { 'X-ELS-APIKey': ELSEVIER_API_KEY, 'Accept': 'application/json', 'x-els-resourceVersion': 'XOCS' } BASE_URL = 'http://api.elsevier.com/content/search/scopus?' ABSTRACT_BASE_URL = 'https://api.elsevier.com/content/abstract/eid/' def to_thread(func: typing.Callable) -> typing.Coroutine: @functools.wraps(func) async def wrapper(*args, **kwargs): return await asyncio.to_thread(func, *args, **kwargs) return wrapper @to_thread def get_summary(result): print("start searching") eid = result.get('eid', None) abstract = get_abstract(eid) if eid else None description = abstract if abstract else result.get( 'dc:description', 'No description available') text = f"タイトル: {result['dc:title']}\n内容: {description}" system = """与えられた論文の要点を以下のフォーマットで日本語で出力してください。タイトルは**で囲み,本文は``で囲んでください,``` **タイトルの日本語訳** ``・どんなもの?`` ``・先行研究と比べてどこがすごい?`` ``・技術や手法のキモはどこ?`` ``・どうやって有効だと検証した?`` ``・議論はある?`` ```""" print(text) print("waiting openai...") response = openai.ChatCompletion.create( model="gpt-4", messages=[ {'role': 'system', 'content': system}, {'role': 'user', 'content': text} ], temperature=0.7, ) print("response is ready") summary = response['choices'][0]['message']['content'] title_en = result['dc:title'] title, *body = summary.split('\n') body = '\n'.join(body) date_str = result['prism:coverDate'] link = result['link'][2]['@href'] message = f"発行日: {date_str}\n{link}\n{title_en}\n{title}\n{body}\n" print("message is ready") return message def get_abstract(eid): abstract_url = f"{ABSTRACT_BASE_URL}{eid}" response = requests.get(abstract_url, headers=HEADERS) response.raise_for_status() abstract_data = response.json() if 'abstracts-retrieval-response' in abstract_data: coredata = abstract_data['abstracts-retrieval-response'].get( 'coredata', None) if coredata: return coredata.get('dc:description', None) return None # インテントの生成 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='$', intents=intents) @bot.event async def on_ready(): print(f'We have logged in as {bot.user}') @bot.command() async def query(ctx, *args): if ctx.author == bot.user: return else: query_arg = ' AND '.join(args) query = f'TITLE-ABS-KEY({query_arg})' print(f"query was set:{query}") # Elsevier APIで最新の論文情報を取得する search_url = f"{BASE_URL}query={query}&count=100&sort=-date&view=STANDARD" response = requests.get(search_url, headers=HEADERS) # Add this line to raise an exception if there's an HTTP error response.raise_for_status() search_results = response.json() print("search done") # searchの結果をリストに格納 if 'search-results' in search_results and 'entry' in search_results['search-results']: result_list = search_results['search-results']['entry'] else: print("Error: Unexpected API response") result_list = [] # ランダムにnum_papersの数だけ選ぶ num_papers = 1 num_papers = min(num_papers, len(result_list)) results = random.sample(result_list, k=num_papers) print("results are ready") # 論文情報をDiscordに投稿する for i, result in enumerate(results): print(f"Processing result {i+1}" + "/" + str(num_papers)) await ctx.channel.send(f"Processing result {i+1}" + "/" + str(num_papers) + " query: " + str({query_arg})) try: msg = str(query_arg)+"の論文です! " + str(i+1) + "/" + str(num_papers) + await get_summary(result) print(f"{msg}") print("done!") await ctx.channel.send(msg) except: print("Error posting message") print(await get_summary(result)) print("bot run") bot.run("")
[ "与えられた論文の要点を以下のフォーマットで日本語で出力してください。タイトルは**で囲み,本文は``で囲んでください,```\n **タイトルの日本語訳**\n ``・どんなもの?``\n ``・先行研究と比べてどこがすごい?``\n ``・技術や手法のキモはどこ?``\n ``・どうやって有効だと検証した?``\n ``・議論はある?``\n ```", "タイトル: PLACEHOLDER\n内容: PLACEHOLDER" ]
2024-01-10
Rakile/Youtube_transcriber
transcriber_v2.py
import asyncio import os import subprocess import sys import threading from boilerplate import API from PySide6.QtCore import QMetaObject, Qt, Slot, QUrl, QSize from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QPushButton, QTextEdit, QComboBox from pytube import YouTube import whisper import time import shutil from openai import OpenAI client = None novelToken = None class YouTubeTranscriber(QWidget): def __init__(self): super().__init__() self.initUI() self.currentModel = "" self.player = QMediaPlayer() def initUI(self): self.resize(QSize(600,600)) # Layout layout = QVBoxLayout(self) # Novel AI persisten api token self.novelai_persistent_api_key = QLineEdit(self) self.novelai_persistent_api_key.setPlaceholderText("<Enter NovelAI Persistent API Token here. Leave blank if you don't have>") layout.addWidget(self.novelai_persistent_api_key) # Novel AI persisten api token self.openai_persistent_api_key = QLineEdit(self) self.openai_persistent_api_key.setPlaceholderText("<Enter OpenAI API Key here. Leave blank if you don't have.>") layout.addWidget(self.openai_persistent_api_key) # YouTube URL input self.url_input = QLineEdit(self) self.url_input.setPlaceholderText("<Enter YouTube URL here, or path to video or audio file.>") layout.addWidget(self.url_input) # Whisper Model Selection Dropdown self.model_selection = QComboBox(self) self.model_selection.addItems(["tiny", "small", "base", "medium", "large"]) layout.addWidget(self.model_selection) #Use engine # Whisper Model Selection Dropdown self.engine_selection = QComboBox(self) self.engine_selection.addItems(["OpenAI", "NovelAI"]) layout.addWidget(self.engine_selection) self.engine_selection.currentTextChanged.connect(self.update_voice_selection) # New Dropdown for Voice Selection OpenAI self.voice_selection = QComboBox(self) self.voice_selection.addItems(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]) layout.addWidget(self.voice_selection) # Download and Transcribe Button self.download_button = QPushButton("Download and Transcribe", self) self.download_button.clicked.connect(self.download_and_transcribe) layout.addWidget(self.download_button) # Transcription result display self.transcription_display = QTextEdit(self) self.transcription_display.setReadOnly(True) layout.addWidget(self.transcription_display) # Stop audio self.stopButton = QPushButton("Stop Audio", self) self.stopButton.clicked.connect(self.stopAudio) layout.addWidget(self.stopButton) self.setLayout(layout) self.setWindowTitle("YouTube Transcriber") def update_voice_selection(self, engine_name): if engine_name == "NovelAI": self.voice_selection.clear() self.voice_selection.addItems(["Ligeia", "Aini", "Orea", "Claea", "Lim", "Aurae", "Naia", "Aulon", "Elei", "Ogma", "Raid", "Pega", "Lam"]) elif engine_name == "OpenAI": self.voice_selection.clear() self.voice_selection.addItems(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]) def get_thread_id(thread): # Returns the thread ID if hasattr(thread, "_thread_id"): return thread._thread_id for id, t in threading._active.items(): if t is thread: return id def stopAudio(self): self.player.stop() self.player.deleteLater() self.player = QMediaPlayer() def download_and_transcribe(self): self.liveview_t = threading.Thread(target=self.downloadandtrans) self.liveview_t.start() def downloadandtrans(self): global client global novelToken if client == None: if self.openai_persistent_api_key.text() != "": client = OpenAI(api_key=self.openai_persistent_api_key.text()) else: client = None elif self.openai_persistent_api_key.text() == "": client = None if novelToken == None: if self.novelai_persistent_api_key.text() != "": novelToken = self.novelai_persistent_api_key.text() else: novelToken = None elif self.novelai_persistent_api_key.text() == "": novelToken = None video_url = self.url_input.text() selected_model = self.model_selection.currentText() if video_url: if video_url.startswith("http"): yt = YouTube(video_url) audio_stream = yt.streams.filter(only_audio=True).first() audio_stream.download(filename='recording.mp3') else: shutil.copyfile(video_url, 'recording.mp3') modelName = self.model_selection.currentText() if modelName != self.currentModel: print("Loading model " + modelName + ".") start = time.time() self.model = whisper.load_model(modelName) end = time.time() print("Loading the model " + modelName + " took:" + str(end - start) + " seconds") self.currentModel = modelName start = time.time() # load audio and pad/trim it to fit 30 seconds audio = whisper.load_audio("recording.mp3") audio = whisper.pad_or_trim(audio) # make log-Mel spectrogram and move to the same device as the model if modelName == "large": mel = whisper.log_mel_spectrogram(audio, n_mels=128).to(self.model.device) else: mel = whisper.log_mel_spectrogram(audio).to(self.model.device) # detect the spoken language _, probs = self.model.detect_language(mel) lang = max(probs, key=probs.get) print(f"Detected language: {max(probs, key=probs.get)}") result = self.model.transcribe("recording.mp3", language=lang, task="translate", fp16=False) # result = model.transcribe("recording.mp3", fp16=False) # make log-Mel spectrogram and move to the same device as the model mel = whisper.log_mel_spectrogram(audio).to(self.model.device) end = time.time() print("The translation took:" + str(end - start) + " seconds") print(f'The text: \n {result["text"]}') self.current_text = result["text"] QMetaObject.invokeMethod(self, "update_text", Qt.QueuedConnection) @Slot() def update_text(self): self.transcription_display.setText(self.current_text) self.liveaudio = threading.Thread(target=self.playAudio) self.liveaudio.start() async def playAudioNovelAIAsync(self): chunks = [self.current_text[i:i + 999] for i in range(0, len(self.current_text), 999)] print("Number of chunks to make into audio:" + str(len(chunks))) final_audio_file = "output.mp3" for index, chunk in enumerate(chunks): print("-- Processing chunk:" + str(index)) # Generate audio for each chunk async with API(novelToken) as api_handler: api = api_handler.api # encryption_key = api_handler.encryption_key logger = api_handler.logger text = chunk voice = self.voice_selection.currentText() seed = -1 # opus = False opus = False # version = "v1" version = "v2" #logger.info(f"Generating a tts voice for {len(text)} characters of text") tts = await api.low_level.generate_voice(text, voice, seed, opus, version) #logger.info(f"TTS saved in {tts_file}") # Save each audio chunk to a file chunk_file = f"output_chunk_{index}.mp3" #chunk_convert = f"output_chunk_{index}.mp3" print("Writing chunk to:" + str(chunk_file)) if os.path.exists(chunk_file): os.remove(chunk_file) with open(chunk_file, "wb") as f: f.write(tts) f.close() # Concatenate audio files if index == 0: if os.path.exists(final_audio_file): os.remove(final_audio_file) os.rename(chunk_file, final_audio_file) else: if os.path.exists("temp.mp3"): os.remove("temp.mp3") cmd = ["ffmpeg", "-i", f"concat:{final_audio_file}|{chunk_file}", "-acodec", "copy", "temp.mp3", "-map_metadata", "0:1"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) process.wait() print("Stiched piece " + str(index) + " to the whole...") stdout, stderr = process.communicate() if os.path.exists(final_audio_file): os.remove(final_audio_file) os.rename("temp.mp3", final_audio_file) os.remove(chunk_file) if os.path.exists("temp.mp3"): os.remove("temp.mp3") # Play the final concatenated audio file using QMediaPlayer from PySide6 url = final_audio_file self.audio_output = QAudioOutput() self.player.setAudioOutput(self.audio_output) self.player.setSource(url) self.audio_output.setVolume(50) self.player.play() def playAudio(self): currentEngine = self.engine_selection.currentText() if currentEngine == "OpenAI": if client != None: self.playAudioOpenAI() else: if novelToken != None: asyncio.run(self.playAudioNovelAIAsync()) def playAudioOpenAI(self): # Split the text into chunks of 4096 characters chunks = [self.current_text[i:i + 4095] for i in range(0, len(self.current_text), 4095)] print("Number of chunks to make into audio:" + str(len(chunks))) final_audio_file = "output.mp3" # Process and concatenate each chunk for index, chunk in enumerate(chunks): print("-- Processing chunk:" + str(index)) print("----------------------------------") print(str(chunk)) print("----------------------------------") # Generate audio for each chunk response = client.audio.speech.create( model="tts-1", voice=self.voice_selection.currentText(), input=chunk, ) # Save each audio chunk to a file chunk_file = f"output_chunk_{index}.mp3" if os.path.exists(chunk_file): os.remove(chunk_file) response.stream_to_file(chunk_file) # Concatenate audio files if index == 0: if os.path.exists(final_audio_file): os.remove(final_audio_file) os.rename(chunk_file, final_audio_file) else: if os.path.exists("temp.mp3"): os.remove("temp.mp3") cmd = ["ffmpeg", "-i", f"concat:{final_audio_file}|{chunk_file}", "-acodec", "copy", "temp.mp3", "-map_metadata", "0:1"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) print("Stiched piece " + str(index) + " to the whole...") stdout, stderr = process.communicate() if os.path.exists(final_audio_file): os.remove(final_audio_file) os.rename("temp.mp3", final_audio_file) os.remove(chunk_file) if os.path.exists("temp.mp3"): os.remove("temp.mp3") # Play the final concatenated audio file using QMediaPlayer from PySide6 url = final_audio_file self.audio_output = QAudioOutput() self.player.setAudioOutput(self.audio_output) self.player.setSource(url) self.audio_output.setVolume(50) self.player.play() if __name__ == "__main__": app = QApplication(sys.argv) window = YouTubeTranscriber() window.show() sys.exit(app.exec())
[]
2024-01-10
PEPLabs/LANG_CL_EVAL
src~utilities~llm_testing_util.py
import os import requests from langchain_community.chat_models import ChatHuggingFace from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate token = os.environ['HF_TOKEN'] # Ideally, we have this token set. Otherwise, replace with hardcoded HF token. API_URL = os.environ['LLM_ENDPOINT'] headers = {"Authorization": "Bearer " + token} textInput = """ <|system|> You are a pirate chatbot who always responds with Arr!</s> <|user|> {userInput}</s> <|assistant|> """ llm = HuggingFaceEndpoint( endpoint_url=API_URL, task="text2text-generation", model_kwargs={ "max_new_tokens": 200 } ) """ This function is used to wake up the Language Learning Model (LLM) by sending a POST request to the API endpoint. It uses a predefined text input to initiate the wake-up process. The response from the API is printed to the console. """ def llm_wakeup(): response = requests.post(API_URL, json={ "inputs": textInput.format(userInput="Hello, how are you?") }, headers=headers) print(response.json()) """ This function checks the connection to the Language Learning Model (LLM) by generating a response to a predefined greeting. This utilizes the HuggingFaceEndpoint LLM, as opposed to the llm_wakeup() function, which utilizes a direct request to the HuggingFace API. Returns: Response generated by the LLM. """ def llm_connection_check(): return llm.generate(["Hello, how are you?"]) """ This function classifies the relevancy of a given message to a question. It uses a chatbot model to determine if the message properly answers the question. The chatbot responds with "yes" if the message is relevant, and "no" otherwise. STRICTLY used within the context of test_lab.py testing for these labs. Parameters: message (str): The message to be classified. question (str): The question to which the message is supposed to respond. Returns: bool: True if the message is relevant (i.e., it answers the question), False otherwise. """ def classify_relevancy(message, question): prompt = ChatPromptTemplate.from_messages([ SystemMessagePromptTemplate.from_template("You are a chatbot who determines if a given message properly answers a question by " "replying 'yes' or 'no''."), HumanMessagePromptTemplate.from_template("Does the following message answer the question: {question}? message: {message}" ), ]) chat_model = ChatHuggingFace(llm=llm) chain = prompt | chat_model | StrOutputParser() result = chain.invoke({"message": message, "question": question}) print("Result: " + result) print(message) print(question) if "yes" in result.lower(): if "i will respond with 'yes' or 'no'" in result.lower(): print("Message is not relevant") return False else: return True else: print(message) return False
[ "replying 'yes' or 'no''.", "Does the following message answer the question: {question}? message: {message}", "You are a chatbot who determines if a given message properly answers a question by replying 'yes' or 'no''.", "You are a chatbot who determines if a given message properly answers a question by " ]
2024-01-10
PEPLabs/LANG_CL_EVAL
src~main~lab.py
import os from langchain.evaluation import load_evaluator, EvaluatorType from langchain_community.chat_models.huggingface import ChatHuggingFace from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint """ This lab will explore using built-in evaluator criteria, creating custom criteria, and using evaluators. https://python.langchain.com/docs/guides/evaluation/string/criteria_eval_chain """ """ Defining LLM, templates, chat_model, and prompt. No need to edit these. """ llm = HuggingFaceEndpoint( endpoint_url=os.environ['LLM_ENDPOINT'], task="text2text-generation", model_kwargs={ "max_new_tokens": 200, "huggingfacehub_api_token": os.environ['HF_TOKEN'], } ) chat_model = ChatHuggingFace(llm=llm) textInput = """ <|system|> You are a helpful AI that responds to questions concisely, if possible.</s> <|user|> {userInput}</s> <|assistant|> """ """ Your tasks for lab completion are below: -Define a prompt that will be evaluated by the built-in "depth" evaluator. -Define your own custom criteria that will evaluate whether a response returns a mathematical value. -Instantiate an evaluator that utilizes your custom criteria. """ # TODO: Write an input that will pass the built-in "depth" criteria. """In other words, write a question that gets an insightful or "deep" answer from the llm""" depth_criteria_passing_query = "" # This is a sample custom criteria that will evaluate whether a response contains spanish words. # Do not edit this, use it as a template for the task below sample_custom_criteria = { "spanish": "Does the output contain words from the spanish language?" } # TODO: create your own custom criteria that evaluates whether a response returns a mathematical value your_custom_criteria = { "TODO" } """The first 2 functions are responsible for evaluating llm responses. DO NOT EDIT THEM. DO read through the functions along with their prints to the console to get an idea of what each function is doing. You will be responsible for instantiating the evaluator in the 3rd function (custom_mathematical_evaluator). The evaluator will return a VALUE of Y and SCORE of 1 if the answer meets the criteria.""" def built_in_depth_evaluator(query: str): # Initial response from LLM prediction = chat_model.invoke(textInput.format(userInput=query)) # Instantiating an evaluator and using it to evaluate the response based on the built-in "depth" criteria evaluator = load_evaluator(EvaluatorType.CRITERIA, llm=chat_model, criteria="depth") eval_result = evaluator.evaluate_strings(prediction=prediction.content, input=query) # Print results print_results("DEPTH", query, prediction, eval_result) def custom_spanish_evaluator(query: str): # Initial response from LLM prediction = chat_model.invoke(textInput.format(userInput=query)) # Instantiating an evaluator and using it to evaluate the response based on the sample custom criteria evaluator = load_evaluator(EvaluatorType.CRITERIA, criteria=sample_custom_criteria, llm=chat_model) eval_result = evaluator.evaluate_strings(prediction=prediction, input=query) # Print results print_results("SPANISH", query, prediction, eval_result) def custom_mathematical_evaluator(query: str): # Initial response from LLM prediction = chat_model.invoke(textInput.format(userInput=query)) # TODO: instantiate an evaluator that uses your custom criteria, and evaluate the response """ Remember the examples of this in the methods above """ evaluator = "TODO" eval_result = evaluator.evaluate_strings(prediction=prediction, input=query) # Print results print_results("MATHEMATICAL", query, prediction, eval_result) # This is just for testing return eval_result """This function will print the results of evaluations""" def print_results(prompt: str, query: str, prediction, eval_result): print("\nPROMPT : ", prompt) print("INPUT: ", query) print("OUTPUT:", prediction.content) result = (eval_result["value"].replace(" ", "")) print("RESULT: ", result) score = (eval_result["score"]) print("SCORE: ", score) if result == "Y" and score == 1: print("The output passes the " + prompt + " criteria") else: print("The output does not pass the " + prompt + " criteria")
[]
2024-01-10
u-masao/embed-text-recommender
src~models~embedding~sentence_transfomer_embedding.py
""" このモジュールは DummyEmbedding モデルを実装します """ import logging from pprint import pformat from typing import List, Optional import numpy as np from langchain.text_splitter import SentenceTransformersTokenTextSplitter from sentence_transformers import SentenceTransformer from tqdm.contrib import tmap from .embedding_model import EmbeddingStrategy class SentenceTransformerEmbedding(EmbeddingStrategy): """ SentenceTransformer を利用した Embedding 実装です。 """ def __init__( self, model_name_or_filepath: str, chunk_overlap: int = 50, tokens_par_chunk: Optional[int] = None, chunk_method: str = "chunk_split", batch_size: str = 32, **kwargs, ): """ コンストラクタ。 Parameters ------ model_name_or_filepath: str 埋め込みモデル名 chunk_overlap: int チャンクオーバーラップトークン数 tokens_par_chunk: Optional[int] チャンクあたりのトークン数。 デフォルト値 None にすることで自動的にモデルの max_tokens を利用する。 chunk_method: str 埋め込みの計算方法を指定する。以下に対応。 - chunk_split (default) - 各センテンスをチャンクに分割し埋め込みを計算する。 - 埋め込みの平均ベクトルを返す。 - head_only - チャンクに分割せずに埋め込みモデルで処理する。 - モデルの max_tokens のみの埋め込みを計算する batch_size: int embedding 時のバッチサイズ """ self.model_name_or_filepath = model_name_or_filepath self.model = SentenceTransformer(model_name_or_filepath) self.splitter = SentenceTransformersTokenTextSplitter( chunk_overlap=chunk_overlap, model_name=model_name_or_filepath, tokens_per_chunk=tokens_par_chunk, ) self.chunk_method = chunk_method self.batch_size = batch_size # _encode function を設定する if self.chunk_method == "head_only": self._encode = self._head_only_encode elif self.chunk_method == "naive_chunk_split": self._encode = self._naive_split_encode elif self.chunk_method == "chunk_split": self._encode = self._make_chunk_averaged_encode else: raise ValueError( "指定の chunk_method には対応していません: " f"chunk_method: {chunk_method}" ) def get_embed_dimension(self) -> int: """ モデルの次元数を返す Parameters ------ None Returns ------ int モデルの次元数 """ return self.model.get_sentence_embedding_dimension() def get_model_name(self) -> str: """ モデルの次元数を返す Parameters ------ None Returns ------ str モデルの名前 """ return self.model_name_or_filepath def embed(self, sentences: List[str]): """ 埋め込みを計算する。 Parameters ------ sentences: List[str] センテンスの List Returns ------ numpy.ndarray 埋め込み行列。埋め込み次元 d とすると以下の行列やベクトルを返す。 - センテンスの数 1 - (d, ) の 1 次元ベクトル - センテンスの数 n (n>1) - (n, d) の行列 """ # remove empty sentence sentences = [x for x in sentences if x] return self._encode(sentences) def _head_only_encode(self, sentences): return self.model.encode(sentences, batch_size=self.batch_size) def _naive_split_encode(self, sentences): embeddings = [] for sentence in sentences: vectors = self.model.encode( self.splitter.split_text(sentence), batch_size=self.batch_size ) mean_vector = np.mean(vectors, axis=0) assert ( mean_vector.shape[0] == self.model.get_sentence_embedding_dimension() ) embeddings.append(mean_vector) result = np.array(embeddings) assert result.shape[0] == len(sentences) assert result.shape[1] == self.model.get_sentence_embedding_dimension() return result def _make_chunk_averaged_encode(self, sentences: List[str]) -> np.ndarray: """ センテンス毎のチャンク List を受け取り、センテンス毎の 平均埋め込みベクトルを返す。 Parameters ------ sentences: List[str] センテンスのリスト Returns ------ numpy.ndarray センテンス毎の埋め込み表現 次元は、センテンス数 n、モデル次元 d に対して、(n, d)となる。 """ # init logger logger = logging.getLogger(__name__) d_size = self.model.get_sentence_embedding_dimension() # split to chunks logger.info("split sentences to chunks") chunks_list = [ x for x in tmap( lambda x: self.splitter.split_text(text=x), sentences ) ] # チャンクを 1 次元の List に flatten する chunk_list = flatten_chunks(chunks_list) # matrix mask を作成 logger.info("make weight matrix") weight_matrix = make_weight_matrix(chunks_list) assert weight_matrix.shape[0] == len(chunks_list) assert weight_matrix.shape[1] == len(chunk_list) # 埋め込みを計算 logger.info("encode chunks") chunk_embeddings = self.model.encode( chunk_list, batch_size=self.batch_size ) assert chunk_embeddings.shape[0] == weight_matrix.shape[1] assert chunk_embeddings.shape[1] == d_size # ウェイト行列とチャンク毎のEmbeddingで行列積を計算 logger.info("calc dot matrix, weight_matrix @ chunk_embeddings") embeddings = np.dot(weight_matrix, chunk_embeddings) assert embeddings.shape[0] == len(chunks_list) assert embeddings.shape[1] == d_size return embeddings def __str__(self) -> str: params = { "model": self.model, "splitter": self.splitter, "model_name_or_filepath": self.model_name_or_filepath, "chunk_method": self.chunk_method, "batch_size": self.batch_size, } return pformat(params) def make_weight_matrix(chunks_list: List[List[str]]) -> np.ndarray: """ チャンク分割された文字列を結合するための行列を作る。 オリジナルのテキスト数が n_size となる。 チャンク分割されたテキスト数が c_size となる。 Parameters ------ chunks_list: List[List[str]] チャンク分割された文字列。それぞれの要素内の要素数が異なる。 Returns ------ numpy.ndarray 結合するためのマスクを返す。 """ # 出力の次元を計算する n_size = len(chunks_list) c_size = np.sum([x for x in map(lambda x: len(x), chunks_list)]) # 出力する変数を初期化 weight_matrix = np.zeros((n_size, c_size)) # offset を定義 chunk_offset = 0 # 各オリジナルテキストの各チャンクでループ for n_index, chunks in enumerate(chunks_list): for c_index, chunk in enumerate(chunks): # Mask Matrix に重みを代入 weight_matrix[n_index, c_index + chunk_offset] = 1 / len(chunks) chunk_offset += len(chunks) # サイズチェックと値チェック assert weight_matrix.sum() - n_size < 1.0e-9 assert np.mean(weight_matrix.sum(axis=1) ** 2) - 1 < 1.0e-9 return weight_matrix def flatten_chunks(chunks_list: List[List[str]]) -> List[str]: """ チャンクを一次元の List に再配置する。 chunks_list -> chunk_list Parameters ------ chunks_list: List[List[str]] 配列内の配列としてチャンクを保持するデータ Returns ------ List[str] チャンクの List """ chunk_list = [] for chunks in chunks_list: for chunk in chunks: chunk_list.append(chunk) return chunk_list
[]
2024-01-10
IrisLi17/self-imitation-via-reduction
baselines~ppo_sir~ppo_sir.py
import time import sys import multiprocessing from collections import deque import gym import numpy as np import tensorflow as tf from stable_baselines import logger from stable_baselines.common import explained_variance, ActorCriticRLModel, tf_util, SetVerbosity, TensorboardWriter from stable_baselines.common.runners import AbstractEnvRunner from stable_baselines.common.policies import ActorCriticPolicy, RecurrentActorCriticPolicy from stable_baselines.a2c.utils import total_episode_reward_logger from utils.eval_stack import pp_eval_model class PPO2_SIR(ActorCriticRLModel): """ Proximal Policy Optimization algorithm (GPU version). Paper: https://arxiv.org/abs/1707.06347 :param policy: (ActorCriticPolicy or str) The policy model to use (MlpPolicy, CnnPolicy, CnnLstmPolicy, ...) :param env: (Gym environment or str) The environment to learn from (if registered in Gym, can be str) :param gamma: (float) Discount factor :param n_steps: (int) The number of steps to run for each environment per update (i.e. batch size is n_steps * n_env where n_env is number of environment copies running in parallel) :param ent_coef: (float) Entropy coefficient for the loss calculation :param learning_rate: (float or callable) The learning rate, it can be a function :param vf_coef: (float) Value function coefficient for the loss calculation :param max_grad_norm: (float) The maximum value for the gradient clipping :param lam: (float) Factor for trade-off of bias vs variance for Generalized Advantage Estimator :param nminibatches: (int) Number of training minibatches per update. For recurrent policies, the number of environments run in parallel should be a multiple of nminibatches. :param noptepochs: (int) Number of epoch when optimizing the surrogate :param cliprange: (float or callable) Clipping parameter, it can be a function :param cliprange_vf: (float or callable) Clipping parameter for the value function, it can be a function. This is a parameter specific to the OpenAI implementation. If None is passed (default), then `cliprange` (that is used for the policy) will be used. IMPORTANT: this clipping depends on the reward scaling. To deactivate value function clipping (and recover the original PPO implementation), you have to pass a negative value (e.g. -1). :param verbose: (int) the verbosity level: 0 none, 1 training information, 2 tensorflow debug :param tensorboard_log: (str) the log location for tensorboard (if None, no logging) :param _init_setup_model: (bool) Whether or not to build the network at the creation of the instance :param policy_kwargs: (dict) additional arguments to be passed to the policy on creation :param full_tensorboard_log: (bool) enable additional logging when using tensorboard WARNING: this logging can take a lot of space quickly """ def __init__(self, policy, env, aug_env=None, eval_env=None, gamma=0.99, n_steps=128, ent_coef=0.01, learning_rate=2.5e-4, vf_coef=0.5, aug_clip=0.1, max_grad_norm=0.5, lam=0.95, nminibatches=4, noptepochs=4, cliprange=0.2, cliprange_vf=None, n_candidate=4, dim_candidate=2, parallel=False, reuse_times=1, start_augment=0, horizon=100, aug_adv_weight=1.0, curriculum=False, self_imitate=False, sil_clip=0.2, log_trace=False, verbose=0, tensorboard_log=None, _init_setup_model=True, policy_kwargs=None, full_tensorboard_log=False): super(PPO2_SIR, self).__init__(policy=policy, env=env, verbose=verbose, requires_vec_env=True, _init_setup_model=_init_setup_model, policy_kwargs=policy_kwargs) self.aug_env = aug_env self.eval_env = eval_env self.learning_rate = learning_rate self.cliprange = cliprange self.cliprange_vf = cliprange_vf self.n_steps = n_steps self.ent_coef = ent_coef self.vf_coef = vf_coef self.aug_clip = aug_clip self.max_grad_norm = max_grad_norm self.gamma = gamma self.lam = lam self.nminibatches = nminibatches self.noptepochs = noptepochs self.n_candidate = n_candidate self.dim_candidate = dim_candidate self.parallel = parallel self.start_augment = start_augment self.curriculum = curriculum self.self_imitate = self_imitate self.sil_clip = sil_clip self.log_trace = log_trace self.tensorboard_log = tensorboard_log self.full_tensorboard_log = full_tensorboard_log self.graph = None self.sess = None self.action_ph = None self.advs_ph = None self.rewards_ph = None self.old_neglog_pac_ph = None self.old_vpred_ph = None self.learning_rate_ph = None self.clip_range_ph = None self.entropy = None self.vf_loss = None self.pg_loss = None self.approxkl = None self.clipfrac = None self.params = None self._train = None self.loss_names = None self.train_model = None self.act_model = None self.step = None self.proba_step = None self.value = None self.initial_state = None self.n_batch = None self.summary = None self.episode_reward = None self.reuse_times = reuse_times self.aug_obs = [] self.aug_act = [] self.aug_neglogp = [] self.aug_return = [] self.aug_value = [] self.aug_done = [] self.aug_reward = [] self.is_selfaug = [] self.num_aug_steps = 0 # every interaction with simulator should be counted self.horizon = horizon self.aug_adv_weight = aug_adv_weight if _init_setup_model: self.setup_model() def _get_pretrain_placeholders(self): policy = self.act_model if isinstance(self.action_space, gym.spaces.Discrete): return policy.obs_ph, self.action_ph, policy.policy return policy.obs_ph, self.action_ph, policy.deterministic_action def setup_model(self): with SetVerbosity(self.verbose): assert issubclass(self.policy, ActorCriticPolicy), "Error: the input policy for the PPO2 model must be " \ "an instance of common.policies.ActorCriticPolicy." self.n_batch = self.n_envs * self.n_steps n_cpu = multiprocessing.cpu_count() if sys.platform == 'darwin': n_cpu //= 2 self.graph = tf.Graph() with self.graph.as_default(): self.sess = tf_util.make_session(num_cpu=n_cpu, graph=self.graph) n_batch_step = None n_batch_train = None if issubclass(self.policy, RecurrentActorCriticPolicy): assert self.n_envs % self.nminibatches == 0, "For recurrent policies, "\ "the number of environments run in parallel should be a multiple of nminibatches." n_batch_step = self.n_envs n_batch_train = self.n_batch // self.nminibatches act_model = self.policy(self.sess, self.observation_space, self.action_space, self.n_envs, 1, n_batch_step, reuse=False, **self.policy_kwargs) with tf.variable_scope("train_model", reuse=True, custom_getter=tf_util.outer_scope_getter("train_model")): train_model = self.policy(self.sess, self.observation_space, self.action_space, self.n_envs // self.nminibatches, self.n_steps, n_batch_train, reuse=True, **self.policy_kwargs) train_aug_model = self.policy(self.sess, self.observation_space, self.action_space, self.n_envs // self.nminibatches, self.n_steps, n_batch_train, reuse=True, **self.policy_kwargs) with tf.variable_scope("loss", reuse=False): self.action_ph = train_model.pdtype.sample_placeholder([None], name="action_ph") self.advs_ph = tf.placeholder(tf.float32, [None], name="advs_ph") self.rewards_ph = tf.placeholder(tf.float32, [None], name="rewards_ph") self.old_neglog_pac_ph = tf.placeholder(tf.float32, [None], name="old_neglog_pac_ph") self.old_vpred_ph = tf.placeholder(tf.float32, [None], name="old_vpred_ph") self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph") self.clip_range_ph = tf.placeholder(tf.float32, [], name="clip_range_ph") self.aug_action_ph = train_aug_model.pdtype.sample_placeholder([None], name="aug_action_ph") self.aug_advs_ph = tf.placeholder(tf.float32, [None], name="aug_advs_ph") self.aug_old_neglog_pac_ph = tf.placeholder(tf.float32, [None], name="aug_old_neglog_pac_ph") neglogpac = train_model.proba_distribution.neglogp(self.action_ph) aug_neglogpac = train_aug_model.proba_distribution.neglogp(self.aug_action_ph) self.entropy = tf.reduce_mean(train_model.proba_distribution.entropy()) vpred = train_model.value_flat # Value function clipping: not present in the original PPO if self.cliprange_vf is None: # Default behavior (legacy from OpenAI baselines): # use the same clipping as for the policy self.clip_range_vf_ph = self.clip_range_ph self.cliprange_vf = self.cliprange elif isinstance(self.cliprange_vf, (float, int)) and self.cliprange_vf < 0: # Original PPO implementation: no value function clipping self.clip_range_vf_ph = None else: # Last possible behavior: clipping range # specific to the value function self.clip_range_vf_ph = tf.placeholder(tf.float32, [], name="clip_range_vf_ph") if self.clip_range_vf_ph is None: # No clipping vpred_clipped = train_model.value_flat else: # Clip the different between old and new value # NOTE: this depends on the reward scaling vpred_clipped = self.old_vpred_ph + \ tf.clip_by_value(train_model.value_flat - self.old_vpred_ph, - self.clip_range_vf_ph, self.clip_range_vf_ph) vf_losses1 = tf.square(vpred - self.rewards_ph) vf_losses2 = tf.square(vpred_clipped - self.rewards_ph) self.vf_loss = .5 * tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2)) ratio = tf.exp(self.old_neglog_pac_ph - neglogpac) if self.self_imitate: if not 'MasspointPush' in self.env.get_attr('spec')[0].id: ratio = tf.exp(tf.minimum(self.old_neglog_pac_ph, 100) - tf.minimum(neglogpac, 100)) else: ratio = tf.exp(tf.minimum(self.old_neglog_pac_ph, 20) - tf.minimum(neglogpac, 20)) else: if 'MasspointPushMultiObstacle' in self.env.get_attr('spec')[0].id: ratio = tf.exp(tf.minimum(self.old_neglog_pac_ph, 20) - neglogpac) # ratio = tf.exp(tf.minimum(self.old_neglog_pac_ph - neglogpac, 10)) pg_losses = -self.advs_ph * ratio pg_losses2 = -self.advs_ph * tf.clip_by_value(ratio, 1.0 - self.clip_range_ph, 1.0 + self.clip_range_ph) # if True: # pg_losses = -tf.clip_by_value(self.advs_ph, -1., 1.) * ratio # pg_losses2 = -tf.clip_by_value(self.advs_ph, -1., 1.) * tf.clip_by_value( # ratio, 1.0 - self.clip_range_ph, 1.0 + self.clip_range_ph) self.pg_loss = tf.reduce_mean(tf.maximum(pg_losses, pg_losses2)) self.approxkl = .5 * tf.reduce_mean(tf.square(neglogpac - self.old_neglog_pac_ph)) self.clipfrac = tf.reduce_mean(tf.cast(tf.greater(tf.abs(ratio - 1.0), self.clip_range_ph), tf.float32)) self.ratio_max = tf.reduce_max(ratio) aug_ratio = tf.exp(self.aug_old_neglog_pac_ph - aug_neglogpac) aug_pg_losses = -self.aug_advs_ph * aug_ratio aug_pg_losses2 = -self.aug_advs_ph * tf.clip_by_value(aug_ratio, 1.0 - self.clip_range_ph, 1.0 + self.clip_range_ph) self.aug_pg_loss = tf.reduce_mean(tf.maximum(aug_pg_losses, aug_pg_losses2)) self.aug_clipfrac = tf.reduce_mean(tf.cast(tf.greater(tf.abs(aug_ratio - 1.0), self.clip_range_ph), tf.float32)) loss = self.pg_loss - self.entropy * self.ent_coef + self.vf_loss * self.vf_coef # loss += self.aug_coef * self.aug_pg_loss tf.summary.scalar('entropy_loss', self.entropy) tf.summary.scalar('policy_gradient_loss', self.pg_loss) tf.summary.scalar('value_function_loss', self.vf_loss) tf.summary.scalar('approximate_kullback-leibler', self.approxkl) tf.summary.scalar('clip_factor', self.clipfrac) tf.summary.scalar('loss', loss) # print(tf.trainable_variables()) with tf.variable_scope('model'): self.params = tf.trainable_variables() # print(self.params) if self.full_tensorboard_log: for var in self.params: tf.summary.histogram(var.name, var) grads = tf.gradients(loss, self.params) if self.max_grad_norm is not None: grads, _grad_norm = tf.clip_by_global_norm(grads, self.max_grad_norm) grads = list(zip(grads, self.params)) trainer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph, epsilon=1e-5) self._train = trainer.apply_gradients(grads) self.loss_names = ['policy_loss', 'value_loss', 'policy_entropy', 'approxkl', 'clipfrac', 'advs_min', 'advs_max', 'ratio_max', 'max_neglogp', 'max_neglogp_origin', 'mean_neglogp'] with tf.variable_scope("input_info", reuse=False): tf.summary.scalar('discounted_rewards', tf.reduce_mean(self.rewards_ph)) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph)) tf.summary.scalar('advantage', tf.reduce_mean(self.advs_ph)) tf.summary.scalar('clip_range', tf.reduce_mean(self.clip_range_ph)) if self.clip_range_vf_ph is not None: tf.summary.scalar('clip_range_vf', tf.reduce_mean(self.clip_range_vf_ph)) tf.summary.scalar('old_neglog_action_probabilty', tf.reduce_mean(self.old_neglog_pac_ph)) tf.summary.scalar('old_value_pred', tf.reduce_mean(self.old_vpred_ph)) if self.full_tensorboard_log: tf.summary.histogram('discounted_rewards', self.rewards_ph) tf.summary.histogram('learning_rate', self.learning_rate_ph) tf.summary.histogram('advantage', self.advs_ph) tf.summary.histogram('clip_range', self.clip_range_ph) tf.summary.histogram('old_neglog_action_probabilty', self.old_neglog_pac_ph) tf.summary.histogram('old_value_pred', self.old_vpred_ph) if tf_util.is_image(self.observation_space): tf.summary.image('observation', train_model.obs_ph) else: tf.summary.histogram('observation', train_model.obs_ph) self.train_model = train_model self.train_aug_model = train_aug_model self.act_model = act_model self.step = act_model.step self.proba_step = act_model.proba_step self.value = act_model.value self.initial_state = act_model.initial_state self.aug_neglogpac_op = aug_neglogpac tf.global_variables_initializer().run(session=self.sess) # pylint: disable=E1101 self.summary = tf.summary.merge_all() def _train_step(self, learning_rate, cliprange, obs, returns, masks, actions, values, neglogpacs, is_demo, update, writer, states=None, cliprange_vf=None, aug_obs_slice=None, aug_act_slice=None, aug_neglog_pac_slice=None, aug_adv_slice=None): """ Training of PPO2 Algorithm :param learning_rate: (float) learning rate :param cliprange: (float) Clipping factor :param obs: (np.ndarray) The current observation of the environment :param returns: (np.ndarray) the rewards :param masks: (np.ndarray) The last masks for done episodes (used in recurent policies) :param actions: (np.ndarray) the actions :param values: (np.ndarray) the values :param neglogpacs: (np.ndarray) Negative Log-likelihood probability of Actions :param update: (int) the current step iteration :param writer: (TensorFlow Summary.writer) the writer for tensorboard :param states: (np.ndarray) For recurrent policies, the internal state of the recurrent model :return: policy gradient loss, value function loss, policy entropy, approximation of kl divergence, updated clipping range, training update operation :param cliprange_vf: (float) Clipping factor for the value function """ advs = returns - values advs = (advs - advs.mean()) / (advs.std() + 1e-8) if not 'MasspointPush' in self.env.get_attr('spec')[0].id: advs = is_demo * np.clip(advs, self.aug_clip, np.inf) * self.aug_adv_weight + (1 - is_demo) * advs else: advs = is_demo * np.clip(advs, 0., 1.) * self.aug_adv_weight + (1 - is_demo) * advs # for i in range(advs.shape[0]): # if is_demo[i]: # if not 'MasspointPush' in self.env.get_attr('spec')[0].id: # advs[i] = np.max([advs[i], self.aug_clip]) * self.aug_adv_weight # else: # advs[i] = np.clip(advs[i], 0., 1.) * self.aug_adv_weight if aug_adv_slice is not None: aug_adv_slice = (aug_adv_slice - aug_adv_slice.mean()) / (aug_adv_slice.std() + 1e-8) td_map = {self.train_model.obs_ph: obs, self.action_ph: actions, self.advs_ph: advs, self.rewards_ph: returns, self.learning_rate_ph: learning_rate, self.clip_range_ph: cliprange, self.old_neglog_pac_ph: neglogpacs, self.old_vpred_ph: values} if states is not None: td_map[self.train_model.states_ph] = states td_map[self.train_model.dones_ph] = masks if aug_obs_slice is not None: td_map[self.train_aug_model.obs_ph] = aug_obs_slice td_map[self.aug_action_ph] = aug_act_slice # td_map[self.aug_advs_ph] = np.max(advs) * np.ones(advs.shape) td_map[self.aug_advs_ph] = aug_adv_slice # print('aug advs mean', np.mean(aug_adv_slice)) td_map[self.aug_old_neglog_pac_ph] = aug_neglog_pac_slice # print('old aug neglog pac mean', np.mean(aug_neglog_pac_slice)) _aug_neglog_pac = self.sess.run(self.aug_neglogpac_op, td_map) # print('aug neglog pac mean', np.mean(_aug_neglog_pac)) # else: # # td_map[self.train_aug_model.obs_ph] = np.zeros(obs.shape) # # td_map[self.aug_action_ph] = np.zeros(actions.shape) # td_map[self.train_aug_model.obs_ph] = obs # td_map[self.aug_action_ph] = actions # td_map[self.aug_advs_ph] = np.zeros(advs.shape) # # td_map[self.aug_old_neglog_pac_ph] = np.zeros(neglogpacs.shape) # td_map[self.aug_old_neglog_pac_ph] = neglogpacs if cliprange_vf is not None and cliprange_vf >= 0: td_map[self.clip_range_vf_ph] = cliprange_vf if states is None: update_fac = self.n_batch // self.nminibatches // self.noptepochs + 1 else: update_fac = self.n_batch // self.nminibatches // self.noptepochs // self.n_steps + 1 if writer is not None: # run loss backprop with summary, but once every 10 runs save the metadata (memory, compute time, ...) if self.full_tensorboard_log and (1 + update) % 10 == 0: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() summary, policy_loss, value_loss, policy_entropy, approxkl, clipfrac, _ = self.sess.run( [self.summary, self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self._train], td_map, options=run_options, run_metadata=run_metadata) writer.add_run_metadata(run_metadata, 'step%d' % (update * update_fac)) else: summary, policy_loss, value_loss, policy_entropy, approxkl, clipfrac, _ = self.sess.run( [self.summary, self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self._train], td_map) writer.add_summary(summary, (update * update_fac)) else: policy_loss, value_loss, policy_entropy, approxkl, clipfrac, ratio_max, _ = self.sess.run( [self.pg_loss, self.vf_loss, self.entropy, self.approxkl, self.clipfrac, self.ratio_max, self._train], td_map) # if aug_obs_slice is not None: # print('demo loss', demo_loss) # exit() if len(np.where(is_demo < 0.5)[0]): original_maxneglogp = np.max(neglogpacs[np.where(is_demo < 0.5)[0]]) else: original_maxneglogp = 0. return policy_loss, value_loss, policy_entropy, approxkl, clipfrac, np.min(advs), np.max(advs), ratio_max, np.max(neglogpacs), original_maxneglogp, np.mean(neglogpacs) def learn(self, total_timesteps, callback=None, seed=None, log_interval=1, tb_log_name="PPO2", reset_num_timesteps=True): # Transform to callable if needed self.learning_rate = get_schedule_fn(self.learning_rate) self.cliprange = get_schedule_fn(self.cliprange) cliprange_vf = get_schedule_fn(self.cliprange_vf) new_tb_log = self._init_num_timesteps(reset_num_timesteps) with SetVerbosity(self.verbose), TensorboardWriter(self.graph, self.tensorboard_log, tb_log_name, new_tb_log) \ as writer: self._setup_learn(seed) if not self.parallel: runner = Runner(env=self.env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, aug_env=self.aug_env, n_candidate=self.n_candidate) elif self.self_imitate: from baselines.ppo_sir.sil_runner import SILRunner runner = SILRunner(env=self.env, aug_env=self.aug_env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, n_candidate=self.n_candidate, dim_candidate=self.dim_candidate, horizon=self.horizon) else: if self.env.get_attr('n_object')[0] > 0: if self.dim_candidate != 3: from baselines.ppo_sir.sir_runner import SIRRunner # runner = ParallelRunner(env=self.env, aug_env=self.aug_env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, # n_candidate=self.n_candidate, horizon=self.horizon) runner = SIRRunner(env=self.env, aug_env=self.aug_env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, n_candidate=self.n_candidate, dim_candidate=self.dim_candidate, horizon=self.horizon, log_trace=self.log_trace) else: # Stacking. from baselines.ppo_sir.sir_runner_stack import SIRRunner runner = SIRRunner(env=self.env, aug_env=self.aug_env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, n_candidate=self.n_candidate, dim_candidate=self.dim_candidate, horizon=self.horizon) else: # Maze. from baselines.ppo_sir.sir_runner_maze import SIRRunner runner = SIRRunner(env=self.env, aug_env=self.aug_env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam, n_candidate=self.n_candidate, dim_candidate=self.dim_candidate, horizon=self.horizon) self.episode_reward = np.zeros((self.n_envs,)) ep_info_buf = deque(maxlen=100) t_first_start = time.time() n_updates = total_timesteps // self.n_batch total_success = 0 original_success = 0 _reuse_times = self.reuse_times start_decay = n_updates pp_sr_buf = deque(maxlen=5) for update in range(1, n_updates + 1): assert self.n_batch % self.nminibatches == 0 batch_size = self.n_batch // self.nminibatches t_start = time.time() frac = 1.0 - (update - 1.0) / n_updates lr_now = self.learning_rate(frac) cliprange_now = self.cliprange(frac) cliprange_vf_now = cliprange_vf(frac) if self.curriculum: if 'FetchStack' in self.env.get_attr('spec')[0].id: # Stacking pp_sr = pp_eval_model(self.eval_env, self) pp_sr_buf.append(pp_sr) print('Pick-and-place success rate', np.mean(pp_sr_buf)) if start_decay == n_updates and np.mean(pp_sr_buf) > 0.8: start_decay = update _ratio = np.clip(0.7 - 0.8 * (update - start_decay) / 380, 0.3, 0.7) # from 0.7 to 0.3 elif 'FetchPushWallObstacle' in self.env.get_attr('spec')[0].id: _ratio = max(1.0 - (update - 1.0) / n_updates, 0.0) else: raise NotImplementedError self.env.env_method('set_random_ratio', _ratio) print('Set random_ratio to', self.env.get_attr('random_ratio')[0]) aug_success_ratio = (total_success - original_success) / (total_success + 1e-8) if aug_success_ratio > 1.0: # if aug_success_ratio > 0.25: _reuse_times -= 1 _reuse_times = max(1, _reuse_times) else: _reuse_times = min(self.reuse_times, _reuse_times + 1) # Reuse goalidx=0 only once # if len(self.aug_obs) and (self.aug_obs[-1] is not None): # other_aug_idx = np.where(self.is_selfaug[-1] < 0.5)[0] # self.aug_obs[-1] = self.aug_obs[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_act[-1] = self.aug_act[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_neglogp[-1] = self.aug_neglogp[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_return[-1] = self.aug_return[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_value[-1] = self.aug_value[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_done[-1] = self.aug_done[-1][other_aug_idx] if len(other_aug_idx) else None # self.aug_reward[-1] = self.aug_reward[-1][other_aug_idx] if len(other_aug_idx) else None # Reuse other data # if _reuse_times > 1 and (not ('MasspointPush' in self.env.get_attr('spec')[0].id) or ('MasspointPush' in self.env.get_attr('spec')[0].id and update > 150)): # if _reuse_times > 1 and (not ('MasspointPush' in self.env.get_attr('spec')[0].id) or ( # 'MasspointPush' in self.env.get_attr('spec')[0].id and update > 100)): if _reuse_times > 1: self.aug_obs = self.aug_obs[-_reuse_times+1:] + [None] self.aug_act = self.aug_act[-_reuse_times+1:] + [None] self.aug_neglogp = self.aug_neglogp[-_reuse_times+1:] + [None] self.aug_return = self.aug_return[-_reuse_times+1:] + [None] self.aug_value = self.aug_value[-_reuse_times+1:] + [None] self.aug_done = self.aug_done[-_reuse_times+1:] + [None] self.aug_reward = self.aug_reward[-_reuse_times+1:] + [None] self.is_selfaug = self.is_selfaug[-_reuse_times+1:] + [None] else: self.aug_obs = [None] self.aug_act = [None] self.aug_neglogp = [None] self.aug_return = [None] self.aug_value = [None] self.aug_done = [None] self.aug_reward = [None] self.is_selfaug = [None] # true_reward is the reward without discount temp_time0 = time.time() obs, returns, masks, actions, values, neglogpacs, states, ep_infos, true_reward = runner.run() is_demo = np.zeros(obs.shape[0]) temp_time1 = time.time() print('runner.run() takes', temp_time1 - temp_time0) original_episodes = np.sum(masks) original_success = np.sum([info['r'] for info in ep_infos]) total_success = original_success # augment_steps = 0 if self.aug_obs is None else self.aug_obs.shape[0] augment_steps = sum([item.shape[0] if item is not None else 0 for item in self.aug_obs]) print([item.shape[0] if item is not None else 0 for item in self.aug_obs]) # if self.aug_obs is not None: if augment_steps > 0: if self.self_imitate and augment_steps / self.n_batch > self.sil_clip: aug_sample_idx = np.random.randint(0, augment_steps, int(self.n_batch * self.sil_clip)) else: aug_sample_idx = np.arange(augment_steps) _aug_return = np.concatenate(list(filter(lambda v:v is not None, self.aug_return)), axis=0) _aug_value = np.concatenate(list(filter(lambda v: v is not None, self.aug_value)), axis=0) adv_clip_frac = np.sum((_aug_return - _aug_value) < (np.mean(returns - values) + self.aug_clip * np.std(returns - values))) / _aug_return.shape[0] print('demo adv below average + %f std' % self.aug_clip, adv_clip_frac) if self.self_imitate: _aug_obs = np.concatenate(list(filter(lambda v: v is not None, self.aug_obs)), axis=0)[aug_sample_idx] obs = np.concatenate([obs, _aug_obs], axis=0) _aug_return = _aug_return[aug_sample_idx] returns = np.concatenate([returns, _aug_return], axis=0) _aug_mask = np.concatenate(list(filter(lambda v: v is not None, self.aug_done)), axis=0)[aug_sample_idx] masks = np.concatenate([masks, _aug_mask], axis=0) _aug_action = np.concatenate(list(filter(lambda v: v is not None, self.aug_act)), axis=0)[aug_sample_idx] actions = np.concatenate([actions, _aug_action], axis=0) _aug_value = np.concatenate(list(filter(lambda v: v is not None, self.aug_value)), axis=0)[aug_sample_idx] values = np.concatenate([values, _aug_value], axis=0) _aug_neglogpac = np.concatenate(list(filter(lambda v: v is not None, self.aug_neglogp)), axis=0)[aug_sample_idx] neglogpacs = np.concatenate([neglogpacs, _aug_neglogpac], axis=0) is_demo = np.concatenate([is_demo, np.ones(len(aug_sample_idx))], axis=0) _aug_reward = np.concatenate(list(filter(lambda v: v is not None, self.aug_reward)), axis=0)[aug_sample_idx] total_success += np.sum(_aug_reward) augment_steps = len(aug_sample_idx) else: obs = np.concatenate([obs, *(list(filter(lambda v:v is not None, self.aug_obs)))], axis=0) returns = np.concatenate([returns, *(list(filter(lambda v:v is not None, self.aug_return)))], axis=0) masks = np.concatenate([masks, *(list(filter(lambda v:v is not None, self.aug_done)))], axis=0) actions = np.concatenate([actions, *(list(filter(lambda v:v is not None, self.aug_act)))], axis=0) values = np.concatenate([values, *(list(filter(lambda v:v is not None, self.aug_value)))], axis=0) neglogpacs = np.concatenate([neglogpacs, *(list(filter(lambda v:v is not None, self.aug_neglogp)))], axis=0) is_demo = np.concatenate([is_demo, np.ones(augment_steps)], axis=0) _aug_reward = np.concatenate(list(filter(lambda v:v is not None, self.aug_reward)), axis=0) total_success += np.sum(_aug_reward) print('augmented data length', obs.shape[0]) self.num_timesteps += self.n_batch ep_info_buf.extend(ep_infos) total_episodes = np.sum(masks) mb_loss_vals = [] if states is None: # nonrecurrent version recompute_neglogp_time = 0 update_fac = self.n_batch // self.nminibatches // self.noptepochs + 1 inds = np.arange(self.n_batch + augment_steps) # print('length self.aug_obs', len(self.aug_obs), batch_size) for epoch_num in range(self.noptepochs): np.random.shuffle(inds) for start in range(0, self.n_batch + augment_steps, batch_size): timestep = self.num_timesteps // update_fac + ((self.noptepochs * self.n_batch + epoch_num * self.n_batch + start) // batch_size) end = start + batch_size mbinds = inds[start:end] _recompute_inds = np.where(is_demo[mbinds] > 0.5)[0] recompute_neglogp_time0 = time.time() if _recompute_inds.shape[0] > 0: neglogpacs[_recompute_inds] = self.sess.run( self.aug_neglogpac_op, {self.train_aug_model.obs_ph: obs[_recompute_inds], self.aug_action_ph: actions[_recompute_inds]}) if self.self_imitate: neglogpacs[_recompute_inds] = np.minimum(neglogpacs[_recompute_inds], 100) recompute_neglogp_time += time.time() - recompute_neglogp_time0 slices = (arr[mbinds] for arr in (obs, returns, masks, actions, values, neglogpacs, is_demo)) # if len(self.aug_obs) > batch_size: # aug_inds = np.random.choice(len(self.aug_obs), batch_size) # aug_obs_slice = np.array(self.aug_obs)[aug_inds] # aug_act_slice = np.array(self.aug_act)[aug_inds] # aug_neglog_pac_slice = np.array(self.aug_neglogp)[aug_inds] # aug_adv_slice = np.array(self.aug_adv)[aug_inds] # else: # aug_obs_slice = None # aug_act_slice = None # aug_neglog_pac_slice = None # aug_adv_slice = None mb_loss_vals.append(self._train_step(lr_now, cliprange_now, *slices, writer=writer, update=timestep, cliprange_vf=cliprange_vf_now, )) else: # recurrent version update_fac = self.n_batch // self.nminibatches // self.noptepochs // self.n_steps + 1 assert self.n_envs % self.nminibatches == 0 env_indices = np.arange(self.n_envs) flat_indices = np.arange(self.n_envs * self.n_steps).reshape(self.n_envs, self.n_steps) envs_per_batch = batch_size // self.n_steps for epoch_num in range(self.noptepochs): np.random.shuffle(env_indices) for start in range(0, self.n_envs, envs_per_batch): timestep = self.num_timesteps // update_fac + ((self.noptepochs * self.n_envs + epoch_num * self.n_envs + start) // envs_per_batch) end = start + envs_per_batch mb_env_inds = env_indices[start:end] mb_flat_inds = flat_indices[mb_env_inds].ravel() slices = (arr[mb_flat_inds] for arr in (obs, returns, masks, actions, values, neglogpacs)) mb_states = states[mb_env_inds] mb_loss_vals.append(self._train_step(lr_now, cliprange_now, *slices, update=timestep, writer=writer, states=mb_states, cliprange_vf=cliprange_vf_now)) print('recompute neglogp time', recompute_neglogp_time) loss_vals = np.mean(mb_loss_vals, axis=0) t_now = time.time() fps = int(self.n_batch / (t_now - t_start)) if writer is not None: self.episode_reward = total_episode_reward_logger(self.episode_reward, true_reward.reshape((self.n_envs, self.n_steps)), masks.reshape((self.n_envs, self.n_steps)), writer, self.num_timesteps) if self.verbose >= 1 and (update % log_interval == 0 or update == 1): explained_var = explained_variance(values, returns) logger.logkv("serial_timesteps", update * self.n_steps) logger.logkv("n_updates", update) logger.logkv("original_timesteps", self.num_timesteps) logger.logkv("total_timesteps", self.num_timesteps + self.num_aug_steps) logger.logkv("fps", fps) logger.logkv("explained_variance", float(explained_var)) if len(ep_info_buf) > 0 and len(ep_info_buf[0]) > 0: logger.logkv('ep_reward_mean', safe_mean([ep_info['r'] for ep_info in ep_info_buf])) logger.logkv('ep_len_mean', safe_mean([ep_info['l'] for ep_info in ep_info_buf])) logger.logkv('time_elapsed', t_start - t_first_start) for (loss_val, loss_name) in zip(loss_vals, self.loss_names): logger.logkv(loss_name, loss_val) logger.logkv("augment_steps", augment_steps) # logger.logkv("original_success", original_success) # logger.logkv("total_success", total_success) logger.logkv("self_aug_ratio", np.mean(runner.self_aug_ratio)) logger.dumpkvs() if callback is not None: # Only stop training if return value is False, not when it is None. This is for backwards # compatibility with callbacks that have no return statement. if callback(locals(), globals()) is False: break return self def save(self, save_path, cloudpickle=False): data = { "gamma": self.gamma, "n_steps": self.n_steps, "vf_coef": self.vf_coef, "ent_coef": self.ent_coef, "max_grad_norm": self.max_grad_norm, "learning_rate": self.learning_rate, "lam": self.lam, "nminibatches": self.nminibatches, "noptepochs": self.noptepochs, "cliprange": self.cliprange, "cliprange_vf": self.cliprange_vf, "verbose": self.verbose, "policy": self.policy, "observation_space": self.observation_space, "action_space": self.action_space, "n_envs": self.n_envs, "_vectorize_action": self._vectorize_action, "policy_kwargs": self.policy_kwargs } params_to_save = self.get_parameters() self._save_to_file(save_path, data=data, params=params_to_save, cloudpickle=cloudpickle) class Runner(AbstractEnvRunner): def __init__(self, *, env, model, n_steps, gamma, lam, aug_env, n_candidate): """ A runner to learn the policy of an environment for a model :param env: (Gym environment) The environment to learn from :param model: (Model) The model to learn :param n_steps: (int) The number of steps to run for each environment :param gamma: (float) Discount factor :param lam: (float) Factor for trade-off of bias vs variance for Generalized Advantage Estimator """ super().__init__(env=env, model=model, n_steps=n_steps) self.lam = lam self.gamma = gamma self.aug_env = aug_env self.n_candidate = n_candidate # obs param self.obs_dim = 40 self.goal_dim = 5 self.n_object = env.unwrapped.n_object # For restart self.ep_state_buf = [[] for _ in range(self.model.n_envs)] self.ep_transition_buf = [[] for _ in range(self.model.n_envs)] def run(self): """ Run a learning step of the model :return: - observations: (np.ndarray) the observations - rewards: (np.ndarray) the rewards - masks: (numpy bool) whether an episode is over or not - actions: (np.ndarray) the actions - values: (np.ndarray) the value function output - negative log probabilities: (np.ndarray) - states: (np.ndarray) the internal states of the recurrent policies - infos: (dict) the extra information of the model """ # mb stands for minibatch mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs = [], [], [], [], [], [] mb_states = self.states ep_infos = [] augment_data_time = 0 for _ in range(self.n_steps): internal_states = self.env.env_method('get_state') for i in range(self.model.n_envs): self.ep_state_buf[i].append(internal_states[i]) actions, values, self.states, neglogpacs = self.model.step(self.obs, self.states, self.dones) mb_obs.append(self.obs.copy()) mb_actions.append(actions) mb_values.append(values) mb_neglogpacs.append(neglogpacs) mb_dones.append(self.dones) clipped_actions = actions # Clip the actions to avoid out of bound error if isinstance(self.env.action_space, gym.spaces.Box): clipped_actions = np.clip(actions, self.env.action_space.low, self.env.action_space.high) self.obs[:], rewards, self.dones, infos = self.env.step(clipped_actions) for info in infos: maybe_ep_info = info.get('episode') if maybe_ep_info is not None: ep_infos.append(maybe_ep_info) mb_rewards.append(rewards) for i in range(self.model.n_envs): # self.ep_transition_buf[i].append((mb_obs[-1][i], mb_actions[-1][i], mb_values[-1][i], # mb_neglogpacs[-1][i], mb_dones[-1][i], mb_rewards[-1][i])) self.ep_transition_buf[i].append((mb_obs[-1][i], mb_actions[-1][i], mb_values[-1][i], mb_neglogpacs[-1][i], mb_dones[-1][i], mb_rewards[-1][i])) # _values = self.env.env_method('augment_data', self.ep_transition_buf, self.ep_state_buf) # print(_values) # exit() temp_time0 = time.time() for idx, done in enumerate(self.dones): if self.model.num_timesteps > self.model.start_augment and done: # Check if this is failture goal = self.ep_transition_buf[idx][0][0][-5:] if np.argmax(goal[3:]) == 0 and (not infos[idx]['is_success']): # Do augmentation # Sample start step and perturbation restart_steps, subgoals = self.select_subgoal(self.ep_transition_buf[idx], k=self.n_candidate) # print('restart steps', restart_steps, 'subgoals', subgoals, 'ultimate goal', goal) # augment_transition_buf = self.ep_transition_buf[idx][:restart_step] for k in range(restart_steps.shape[0]): restart_step = restart_steps[k] subgoal = subgoals[k] if restart_step > 0: augment_obs_buf, augment_act_buf, augment_value_buf, \ augment_neglogp_buf, augment_done_buf, augment_reward_buf = \ zip(*self.ep_transition_buf[idx][:restart_step]) augment_obs_buf = list(augment_obs_buf) augment_act_buf = list(augment_act_buf) augment_value_buf = list(augment_value_buf) augment_neglogp_buf = list(augment_neglogp_buf) augment_done_buf = list(augment_done_buf) augment_reward_buf = list(augment_reward_buf) else: augment_obs_buf, augment_act_buf, augment_value_buf, \ augment_neglogp_buf, augment_done_buf, augment_reward_buf = [], [], [], [], [], [] augment_obs1, augment_act1, augment_value1, augment_neglogp1, augment_done1, augment_reward1, next_state = \ self.rollout_subtask(self.ep_state_buf[idx][restart_step], subgoal, len(augment_obs_buf), goal) if augment_obs1 is not None: # augment_transition_buf += augment_transition1 augment_obs_buf += augment_obs1 augment_act_buf += augment_act1 augment_value_buf += augment_value1 augment_neglogp_buf += augment_neglogp1 augment_done_buf += augment_done1 augment_reward_buf += augment_reward1 augment_obs2, augment_act2, augment_value2, augment_neglogp2, augment_done2, augment_reward2, _ = \ self.rollout_subtask(next_state, goal, len(augment_obs_buf), goal) if augment_obs2 is not None: print('Success') # augment_transition_buf += augment_transition2 augment_obs_buf += augment_obs2 augment_act_buf += augment_act2 augment_value_buf += augment_value2 augment_neglogp_buf += augment_neglogp2 augment_done_buf += augment_done2 augment_reward_buf += augment_reward2 if augment_done_buf[0] != True: augment_done_buf[0] = True assert sum(augment_done_buf) == 1, augment_done_buf augment_returns = self.compute_adv(augment_value_buf, augment_done_buf, augment_reward_buf) assert augment_done_buf[0] == True assert sum(augment_done_buf) == 1 # aug_obs, aug_act = zip(*augment_transition_buf) # print(len(augment_obs_buf), len(augment_act_buf), len(augment_neglogp_buf)) # print(augment_adv_buf) # The augment data is directly passed to model # self.model.aug_obs += list(aug_obs) # self.model.aug_act += list(aug_act) for i in range(len(augment_obs_buf)): assert np.argmax(augment_obs_buf[i][-2:]) == 0 assert np.argmax(augment_obs_buf[i][-7:-5]) == 0 # self.model.aug_obs += augment_obs_buf # self.model.aug_act += augment_act_buf # self.model.aug_neglogp += augment_neglogp_buf # self.model.aug_adv += augment_adv_buf if self.model.aug_obs is None: self.model.aug_obs = np.array(augment_obs_buf) self.model.aug_act = np.array(augment_act_buf) self.model.aug_neglogp = np.array(augment_neglogp_buf) self.model.aug_value = np.array(augment_value_buf) self.model.aug_return = augment_returns self.model.aug_done = np.array(augment_done_buf) else: self.model.aug_obs = np.concatenate([self.model.aug_obs, np.array(augment_obs_buf)], axis=0) self.model.aug_act = np.concatenate([self.model.aug_act, np.array(augment_act_buf)], axis=0) self.model.aug_neglogp = np.concatenate([self.model.aug_neglogp, np.array(augment_neglogp_buf)],axis=0) self.model.aug_value = np.concatenate([self.model.aug_value, np.array(augment_value_buf)], axis=0) self.model.aug_return = np.concatenate([self.model.aug_return, augment_returns], axis=0) self.model.aug_done = np.concatenate([self.model.aug_done, np.array(augment_done_buf)], axis=0) assert self.model.aug_done[0] == True # else: # print('Failed to achieve ultimate goal') # else: # print('Failed to achieve subgoal') # Then update buf self.ep_state_buf[idx] = [] self.ep_transition_buf[idx] = [] temp_time1 = time.time() augment_data_time += (temp_time1 - temp_time0) # batch of steps to batch of rollouts mb_obs = np.asarray(mb_obs, dtype=self.obs.dtype) mb_rewards = np.asarray(mb_rewards, dtype=np.float32) mb_actions = np.asarray(mb_actions) mb_values = np.asarray(mb_values, dtype=np.float32) mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32) mb_dones = np.asarray(mb_dones, dtype=np.bool) last_values = self.model.value(self.obs, self.states, self.dones) # discount/bootstrap off value fn mb_advs = np.zeros_like(mb_rewards) true_reward = np.copy(mb_rewards) last_gae_lam = 0 for step in reversed(range(self.n_steps)): if step == self.n_steps - 1: nextnonterminal = 1.0 - self.dones nextvalues = last_values else: nextnonterminal = 1.0 - mb_dones[step + 1] nextvalues = mb_values[step + 1] delta = mb_rewards[step] + self.gamma * nextvalues * nextnonterminal - mb_values[step] mb_advs[step] = last_gae_lam = delta + self.gamma * self.lam * nextnonterminal * last_gae_lam mb_returns = mb_advs + mb_values mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, true_reward = \ map(swap_and_flatten, (mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, true_reward)) print('augment data takes', augment_data_time) return mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, mb_states, ep_infos, true_reward def select_subgoal(self, transition_buf, k): # self.ep_transition_buf, self.model.value assert len(transition_buf) == 100, len(transition_buf) obs_buf, *_ = zip(*transition_buf) obs_buf = np.asarray(obs_buf) sample_t = np.random.randint(0, len(transition_buf), 4096) sample_obs = obs_buf[sample_t] noise = np.random.uniform(low=-0.15, high=0.15, size=(len(sample_t), 2)) obstacle_xy = sample_obs[:, 6:8] + noise sample_obs[:, 6:8] = obstacle_xy sample_obs[:, 12:14] = sample_obs[:, 6:8] - sample_obs[:, 0:2] value2 = self.model.value(sample_obs) subgoal_obs = obs_buf[sample_t] subgoal_obs[:, 40:43] = subgoal_obs[:, 6:9] subgoal_obs[:, 43:45] = np.array([[0., 1.]]) subgoal_obs[:, 45:47] = obstacle_xy subgoal_obs[:, 47:48] = subgoal_obs[:, 8:9] subgoal_obs[:, 48:50] = np.array([[0., 1.]]) value1 = self.model.value(subgoal_obs) normalize_value1 = (value1 - np.min(value1)) / (np.max(value1) - np.min(value1)) normalize_value2 = (value2 - np.min(value2)) / (np.max(value2) - np.min(value2)) # best_idx = np.argmax(normalize_value1 * normalize_value2) ind = np.argsort(normalize_value1 * normalize_value2) good_ind = ind[-k:] # restart_step = sample_t[best_idx] # subgoal = subgoal_obs[best_idx, 45:50] restart_step = sample_t[good_ind] subgoal = subgoal_obs[good_ind, 45:50] # print('subgoal', subgoal, 'with value1', normalize_value1[best_idx], 'value2', normalize_value2[best_idx]) # print('restart step', restart_step) return restart_step, subgoal def rollout_subtask(self, restart_state, goal, restart_step, ultimate_goal): aug_transition = [] self.aug_env.unwrapped.sim.set_state(restart_state) self.aug_env.unwrapped.sim.forward() self.aug_env.unwrapped.goal[:] = goal dict_obs = self.aug_env.unwrapped.get_obs() obs = np.concatenate([dict_obs[key] for key in ['observation', 'achieved_goal', 'desired_goal']]) # print('subgoal', goal, 'obs', obs[-10:]) def switch_goal(obs, goal): obs = obs.copy() assert len(goal) == 5 obs[-5:] = goal goal_idx = np.argmax(goal[3:]) obs[-10:-5] = np.concatenate([obs[3 + goal_idx * 3 : 6 + goal_idx * 3], goal[3:5]]) return obs info = {'is_success': False} for step_idx in range(restart_step, 100): # If I use subgoal obs, value has problem # If I use ultimate goal obs, action should be rerunned # action, value, _, neglogpac = self.model.step(obs) action, _, _, _ = self.model.step(np.expand_dims(obs, axis=0)) action = np.squeeze(action, axis=0) clipped_actions = action # Clip the actions to avoid out of bound error if isinstance(self.aug_env.action_space, gym.spaces.Box): clipped_actions = np.clip(action, self.aug_env.action_space.low, self.aug_env.action_space.high) next_obs, _, _, info = self.aug_env.step(clipped_actions) self.model.num_aug_steps += 1 reward = self.aug_env.compute_reward(switch_goal(next_obs, ultimate_goal), ultimate_goal, None) next_state = self.aug_env.unwrapped.sim.get_state() # aug_transition.append((obs, action, value, neglogpac, done, reward)) aug_transition.append((switch_goal(obs, ultimate_goal), action, False, reward)) # Note that done refers to the output of previous action # print(step_idx, obs[-10:], next_obs[-10:]) if info['is_success']: break obs = next_obs # print('length of augment transition', len(aug_transition)) if info['is_success']: aug_obs, aug_act, aug_done, aug_reward = zip(*aug_transition) aug_obs = list(aug_obs) aug_act = list(aug_act) aug_done = list(aug_done) aug_reward = list(aug_reward) aug_neglogpac = self.model.sess.run(self.model.aug_neglogpac_op, {self.model.train_aug_model.obs_ph: np.array(aug_obs), self.model.aug_action_ph: np.array(aug_act)}) aug_value = self.model.value(np.array(aug_obs)) # print(aug_neglogpac.shape) aug_neglogpac = aug_neglogpac.tolist() aug_value = aug_value.tolist() # print(np.mean(aug_neglogpac)) return aug_obs, aug_act, aug_value, aug_neglogpac, aug_done, aug_reward, next_state return None, None, None, None, None, None, None def compute_adv(self, values, dones, rewards): if not isinstance(values, np.ndarray): values = np.asarray(values) dones = np.asarray(dones) rewards = np.asarray(rewards) # discount/bootstrap off value fn advs = np.zeros_like(rewards) last_gae_lam = 0 for step in reversed(range(values.shape[0])): if step == values.shape[0] - 1: # Here we have assumed that the episode ends with done=Fase (not recorded in dones!). nextnonterminal = 0.0 # So nextvalues here will not be used. nextvalues = np.zeros(values[0].shape) else: nextnonterminal = 1.0 - dones[step + 1] nextvalues = values[step + 1] delta = rewards[step] + self.gamma * nextvalues * nextnonterminal - values[step] advs[step] = last_gae_lam = delta + self.gamma * self.lam * nextnonterminal * last_gae_lam returns = advs + values return returns def get_schedule_fn(value_schedule): """ Transform (if needed) learning rate and clip range to callable. :param value_schedule: (callable or float) :return: (function) """ # If the passed schedule is a float # create a constant function if isinstance(value_schedule, (float, int)): # Cast to float to avoid errors value_schedule = constfn(float(value_schedule)) else: assert callable(value_schedule) return value_schedule # obs, returns, masks, actions, values, neglogpacs, states = runner.run() def swap_and_flatten(arr): """ swap and then flatten axes 0 and 1 :param arr: (np.ndarray) :return: (np.ndarray) """ shape = arr.shape return arr.swapaxes(0, 1).reshape(shape[0] * shape[1], *shape[2:]) def constfn(val): """ Create a function that returns a constant It is useful for learning rate schedule (to avoid code duplication) :param val: (float) :return: (function) """ def func(_): return val return func def safe_mean(arr): """ Compute the mean of an array if there is at least one element. For empty array, return nan. It is used for logging only. :param arr: (np.ndarray) :return: (float) """ return np.nan if len(arr) == 0 else np.mean(arr)
[]
2024-01-10
IrisLi17/self-imitation-via-reduction
baselines~sac_sir~sac_sir.py
import sys, os, csv, gym import time import multiprocessing from collections import deque import warnings import numpy as np import tensorflow as tf from stable_baselines.a2c.utils import total_episode_reward_logger from stable_baselines.common import tf_util, OffPolicyRLModel, SetVerbosity, TensorboardWriter from stable_baselines.common.vec_env import VecEnv from utils.replay_buffer import MultiWorkerReplayBuffer, PrioritizedMultiWorkerReplayBuffer from utils.replay_buffer import DoublePrioritizedReplayWrapper from stable_baselines.ppo2.ppo2 import safe_mean, get_schedule_fn from stable_baselines.sac.policies import SACPolicy from stable_baselines import logger from utils.eval_stack import eval_model def get_vars(scope): """ Alias for get_trainable_vars :param scope: (str) :return: [tf Variable] """ return tf_util.get_trainable_vars(scope) class SAC_SIR(OffPolicyRLModel): """ Soft Actor-Critic (SAC) Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor, This implementation borrows code from original implementation (https://github.com/haarnoja/sac) from OpenAI Spinning Up (https://github.com/openai/spinningup) and from the Softlearning repo (https://github.com/rail-berkeley/softlearning/) Paper: https://arxiv.org/abs/1801.01290 Introduction to SAC: https://spinningup.openai.com/en/latest/algorithms/sac.html :param policy: (SACPolicy or str) The policy model to use (MlpPolicy, CnnPolicy, LnMlpPolicy, ...) :param env: (Gym environment or str) The environment to learn from (if registered in Gym, can be str) :param gamma: (float) the discount factor :param learning_rate: (float or callable) learning rate for adam optimizer, the same learning rate will be used for all networks (Q-Values, Actor and Value function) it can be a function of the current progress (from 1 to 0) :param buffer_size: (int) size of the replay buffer :param batch_size: (int) Minibatch size for each gradient update :param tau: (float) the soft update coefficient ("polyak update", between 0 and 1) :param ent_coef: (str or float) Entropy regularization coefficient. (Equivalent to inverse of reward scale in the original SAC paper.) Controlling exploration/exploitation trade-off. Set it to 'auto' to learn it automatically (and 'auto_0.1' for using 0.1 as initial value) :param train_freq: (int) Update the model every `train_freq` steps. :param learning_starts: (int) how many steps of the model to collect transitions for before learning starts :param target_update_interval: (int) update the target network every `target_network_update_freq` steps. :param gradient_steps: (int) How many gradient update after each step :param target_entropy: (str or float) target entropy when learning ent_coef (ent_coef = 'auto') :param action_noise: (ActionNoise) the action noise type (None by default), this can help for hard exploration problem. Cf DDPG for the different action noise type. :param random_exploration: (float) Probability of taking a random action (as in an epsilon-greedy strategy) This is not needed for SAC normally but can help exploring when using HER + SAC. This hack was present in the original OpenAI Baselines repo (DDPG + HER) :param verbose: (int) the verbosity level: 0 none, 1 training information, 2 tensorflow debug :param tensorboard_log: (str) the log location for tensorboard (if None, no logging) :param _init_setup_model: (bool) Whether or not to build the network at the creation of the instance :param policy_kwargs: (dict) additional arguments to be passed to the policy on creation :param full_tensorboard_log: (bool) enable additional logging when using tensorboard Note: this has no effect on SAC logging for now """ def __init__(self, policy, env, trained_sac_model=None, gamma=0.99, learning_rate=3e-4, buffer_size=50000, priority_buffer=False, alpha=0.6, learning_starts=100, train_freq=1, batch_size=64, tau=0.005, ent_coef='auto', target_update_interval=1, gradient_steps=1, target_entropy='auto', action_noise=None, random_exploration=0.0, n_subgoal=2, start_augment_time=0, aug_env=None, eval_env=None, curriculum=False, imitation_coef=5, sequential=False, verbose=0, tensorboard_log=None, _init_setup_model=True, policy_kwargs=None, full_tensorboard_log=False): super(SAC_SIR, self).__init__(policy=policy, env=env, replay_buffer=None, verbose=verbose, policy_base=SACPolicy, requires_vec_env=False, policy_kwargs=policy_kwargs) self.aug_env = aug_env self.eval_env = eval_env self.trained_sac_model = trained_sac_model self.buffer_size = buffer_size self.learning_rate = learning_rate self.learning_starts = learning_starts self.train_freq = train_freq self.batch_size = batch_size self.tau = tau # In the original paper, same learning rate is used for all networks # self.policy_lr = learning_rate # self.qf_lr = learning_rate # self.vf_lr = learning_rate # Entropy coefficient / Entropy temperature # Inverse of the reward scale self.ent_coef = ent_coef self.target_update_interval = target_update_interval self.gradient_steps = gradient_steps self.gamma = gamma self.action_noise = action_noise self.random_exploration = random_exploration self.n_subgoal = n_subgoal self.start_augment_time = start_augment_time self.priority_buffer = priority_buffer self.alpha = alpha self.curriculum = curriculum self.imitation_coef = imitation_coef self.sequential = sequential self.value_fn = None self.graph = None self.replay_buffer = None self.augment_replay_buffer = None self.combined_replay_buffer = None self.episode_reward = None self.sess = None self.tensorboard_log = tensorboard_log self.verbose = verbose self.params = None self.summary = None self.policy_tf = None self.target_entropy = target_entropy self.full_tensorboard_log = full_tensorboard_log self.obs_target = None self.target_policy = None self.actions_ph = None self.rewards_ph = None self.terminals_ph = None self.observations_ph = None self.action_target = None self.next_observations_ph = None self.value_target = None self.step_ops = None self.target_update_op = None self.infos_names = None self.entropy = None self.target_params = None self.learning_rate_ph = None self.processed_obs_ph = None self.processed_next_obs_ph = None self.log_ent_coef = None self.num_aug_steps = 0 if _init_setup_model: self.setup_model() def _get_pretrain_placeholders(self): policy = self.policy_tf # Rescale deterministic_action = self.deterministic_action * np.abs(self.action_space.low) return policy.obs_ph, self.actions_ph, deterministic_action def setup_model(self): with SetVerbosity(self.verbose): self.graph = tf.Graph() with self.graph.as_default(): n_cpu = multiprocessing.cpu_count() if sys.platform == 'darwin': n_cpu //= 2 self.sess = tf_util.make_session(num_cpu=n_cpu, graph=self.graph) if hasattr(self.env, "env") and isinstance(self.env.env, VecEnv): self.n_envs = self.env.env.num_envs else: self.n_envs = 1 if self.priority_buffer: self.replay_buffer = PrioritizedMultiWorkerReplayBuffer(self.buffer_size, self.alpha, num_workers=self.env.env.num_envs, gamma=self.gamma) self.augment_replay_buffer = PrioritizedMultiWorkerReplayBuffer(self.buffer_size, self.alpha, num_workers=1, gamma=self.gamma) else: self.replay_buffer = MultiWorkerReplayBuffer(self.buffer_size, num_workers=self.n_envs, gamma=self.gamma) self.augment_replay_buffer = MultiWorkerReplayBuffer(self.buffer_size, num_workers=1, gamma=self.gamma) with tf.variable_scope("input", reuse=False): # Create policy and target TF objects self.policy_tf = self.policy(self.sess, self.observation_space, self.action_space, **self.policy_kwargs) self.target_policy = self.policy(self.sess, self.observation_space, self.action_space, **self.policy_kwargs) # Initialize Placeholders self.observations_ph = self.policy_tf.obs_ph # Normalized observation for pixels self.processed_obs_ph = self.policy_tf.processed_obs self.next_observations_ph = self.target_policy.obs_ph self.processed_next_obs_ph = self.target_policy.processed_obs self.action_target = self.target_policy.action_ph self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals') self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards') self.actions_ph = tf.placeholder(tf.float32, shape=(None,) + self.action_space.shape, name='actions') self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph") self.importance_weight_ph = tf.placeholder(tf.float32, shape=(None,), name="weights") # self.sum_rs_ph = tf.placeholder(tf.float32, shape=(None, 1), name="sum_rs") with tf.variable_scope("model", reuse=False): # Create the policy # first return value corresponds to deterministic actions # policy_out corresponds to stochastic actions, used for training # logp_pi is the log probabilty of actions taken by the policy self.deterministic_action, policy_out, logp_pi = self.policy_tf.make_actor(self.processed_obs_ph) # Monitor the entropy of the policy, # this is not used for training self.entropy = tf.reduce_mean(self.policy_tf.entropy) # Use two Q-functions to improve performance by reducing overestimation bias. qf1, qf2, value_fn = self.policy_tf.make_critics(self.processed_obs_ph, self.actions_ph, create_qf=True, create_vf=True) qf1_pi, qf2_pi, _ = self.policy_tf.make_critics(self.processed_obs_ph, policy_out, create_qf=True, create_vf=False, reuse=True) # Target entropy is used when learning the entropy coefficient if self.target_entropy == 'auto': # automatically set target entropy if needed self.target_entropy = -np.prod(self.env.action_space.shape).astype(np.float32) else: # Force conversion # this will also throw an error for unexpected string self.target_entropy = float(self.target_entropy) # The entropy coefficient or entropy can be learned automatically # see Automating Entropy Adjustment for Maximum Entropy RL section # of https://arxiv.org/abs/1812.05905 if isinstance(self.ent_coef, str) and self.ent_coef.startswith('auto'): # Default initial value of ent_coef when learned init_value = 1.0 if '_' in self.ent_coef: init_value = float(self.ent_coef.split('_')[1]) assert init_value > 0., "The initial value of ent_coef must be greater than 0" self.log_ent_coef = tf.get_variable('log_ent_coef', dtype=tf.float32, initializer=np.log(init_value).astype(np.float32)) self.ent_coef = tf.exp(self.log_ent_coef) else: # Force conversion to float # this will throw an error if a malformed string (different from 'auto') # is passed self.ent_coef = float(self.ent_coef) with tf.variable_scope("target", reuse=False): # Create the value network _, _, value_target = self.target_policy.make_critics(self.processed_next_obs_ph, create_qf=False, create_vf=True) self.value_target = value_target with tf.variable_scope("loss", reuse=False): # Take the min of the two Q-Values (Double-Q Learning) min_qf_pi = tf.minimum(qf1_pi, qf2_pi) # Target for Q value regression q_backup = tf.stop_gradient( self.rewards_ph + (1 - self.terminals_ph) * self.gamma * self.value_target ) # Compute Q-Function loss # TODO: test with huber loss (it would avoid too high values) qf1_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (q_backup - qf1) ** 2) qf2_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (q_backup - qf2) ** 2) # Compute the entropy temperature loss # it is used when the entropy coefficient is learned ent_coef_loss, entropy_optimizer = None, None if not isinstance(self.ent_coef, float): ent_coef_loss = -tf.reduce_mean( self.log_ent_coef * tf.stop_gradient(logp_pi + self.target_entropy)) entropy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) # Compute the policy loss # Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi) policy_kl_loss = tf.reduce_mean(self.ent_coef * logp_pi - qf1_pi) # self.is_demo_ph = tf.placeholder(tf.float32, shape=(None,), name='is_demo') # Behavior cloning loss # policy_imitation_loss = tf.reduce_mean( # self.is_demo_ph * tf.reduce_mean(tf.square(self.deterministic_action - self.actions_ph), # axis=-1) * tf.stop_gradient(tf.cast(tf.greater(qf1, qf1_pi), tf.float32))) # Self imitation style loss self.logpac_op = logp_ac = self.logpac(self.actions_ph) policy_imitation_loss = tf.reduce_mean( (-logp_ac * tf.stop_gradient(tf.nn.relu(qf1 - value_fn)))) # NOTE: in the original implementation, they have an additional # regularization loss for the gaussian parameters # this is not used for now # policy_loss = (policy_kl_loss + policy_regularization_loss) policy_loss = policy_kl_loss + self.imitation_coef * policy_imitation_loss # Target for value fn regression # We update the vf towards the min of two Q-functions in order to # reduce overestimation bias from function approximation error. v_backup = tf.stop_gradient(min_qf_pi - self.ent_coef * logp_pi) value_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (value_fn - v_backup) ** 2) values_losses = qf1_loss + qf2_loss + value_loss # Policy train op # (has to be separate from value train op, because min_qf_pi appears in policy_loss) policy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) policy_train_op = policy_optimizer.minimize(policy_loss, var_list=get_vars('model/pi')) # Value train op value_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) values_params = get_vars('model/values_fn') source_params = get_vars("model/values_fn/vf") target_params = get_vars("target/values_fn/vf") # Polyak averaging for target variables self.target_update_op = [ tf.assign(target, (1 - self.tau) * target + self.tau * source) for target, source in zip(target_params, source_params) ] # Initializing target to match source variables target_init_op = [ tf.assign(target, source) for target, source in zip(target_params, source_params) ] # Control flow is used because sess.run otherwise evaluates in nondeterministic order # and we first need to compute the policy action before computing q values losses with tf.control_dependencies([policy_train_op]): train_values_op = value_optimizer.minimize(values_losses, var_list=values_params) self.infos_names = ['policy_loss', 'qf1_loss', 'qf2_loss', 'value_loss', 'entropy', 'demo_ratio'] # All ops to call during one training step self.step_ops = [policy_loss, qf1_loss, qf2_loss, value_loss, qf1, qf2, value_fn, logp_pi, self.entropy, policy_train_op, train_values_op] # Add entropy coefficient optimization operation if needed if ent_coef_loss is not None: with tf.control_dependencies([train_values_op]): ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef) self.infos_names += ['ent_coef_loss', 'ent_coef'] self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef] # Monitor losses and entropy in tensorboard tf.summary.scalar('policy_loss', policy_loss) tf.summary.scalar('qf1_loss', qf1_loss) tf.summary.scalar('qf2_loss', qf2_loss) tf.summary.scalar('value_loss', value_loss) tf.summary.scalar('entropy', self.entropy) if ent_coef_loss is not None: tf.summary.scalar('ent_coef_loss', ent_coef_loss) tf.summary.scalar('ent_coef', self.ent_coef) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph)) # Retrieve parameters that must be saved self.params = get_vars("model") self.target_params = get_vars("target/values_fn/vf") # Initialize Variables and target network with self.sess.as_default(): self.sess.run(tf.global_variables_initializer()) self.sess.run(target_init_op) self.summary = tf.summary.merge_all() def _train_step(self, step, writer, learning_rate): def safe_concat(arr1, arr2): if len(arr1) == 0: return arr2 if len(arr2) == 0: return arr1 return np.concatenate([arr1, arr2]) if self.priority_buffer: batch1, batch2 = self.combined_replay_buffer.sample(self.batch_size, beta=0.4) batch1_obs, batch1_actions, batch1_rewards, batch1_next_obs, batch1_dones, batch1_weights, batch1_idxes = batch1 batch2_obs, batch2_actions, batch2_rewards, batch2_next_obs, batch2_dones, batch2_weights, batch2_idxes = batch2 batch_obs = safe_concat(batch1_obs, batch2_obs) batch_actions = safe_concat(batch1_actions, batch2_actions) batch_rewards = safe_concat(batch1_rewards, batch2_rewards) batch_next_obs = safe_concat(batch1_next_obs, batch2_next_obs) batch_dones = safe_concat(batch1_dones, batch2_dones) # batch_sumrs = safe_concat(batch1_sumrs, batch2_sumrs) batch_weights = safe_concat(batch1_weights, batch2_weights) batch_is_demo = safe_concat(np.zeros(batch1_obs.shape[0], dtype=np.float32), np.ones(batch2_obs.shape[0], dtype=np.float32)) demo_ratio = batch2_obs.shape[0] / batch_obs.shape[0] else: # Uniform sampling n_augment = int(self.batch_size * (len(self.augment_replay_buffer) / (len(self.augment_replay_buffer) + len(self.replay_buffer)))) if n_augment > 0 and self.augment_replay_buffer.can_sample(n_augment): batch1 = self.replay_buffer.sample(self.batch_size - n_augment) batch2 = self.augment_replay_buffer.sample(n_augment) batch1_obs, batch1_actions, batch1_rewards, batch1_next_obs, batch1_dones = batch1 batch2_obs, batch2_actions, batch2_rewards, batch2_next_obs, batch2_dones = batch2 batch_obs = safe_concat(batch1_obs, batch2_obs) batch_actions = safe_concat(batch1_actions, batch2_actions) batch_rewards = safe_concat(batch1_rewards, batch2_rewards) batch_next_obs = safe_concat(batch1_next_obs, batch2_next_obs) batch_dones = safe_concat(batch1_dones, batch2_dones) # batch_sumrs = safe_concat(batch1_sumrs, batch2_sumrs) batch_is_demo = safe_concat(np.zeros(batch1_obs.shape[0], dtype=np.float32), np.ones(batch2_obs.shape[0], dtype=np.float32)) demo_ratio = batch2_obs.shape[0] / batch_obs.shape[0] else: batch = self.replay_buffer.sample(self.batch_size) batch_obs, batch_actions, batch_rewards, batch_next_obs, batch_dones = batch batch_is_demo = np.zeros(batch_obs.shape[0], dtype=np.float32) demo_ratio = 0.0 batch_weights = np.ones(batch_obs.shape[0]) feed_dict = { self.observations_ph: batch_obs, self.actions_ph: batch_actions, self.next_observations_ph: batch_next_obs, self.rewards_ph: batch_rewards.reshape(self.batch_size, -1), self.terminals_ph: batch_dones.reshape(self.batch_size, -1), self.learning_rate_ph: learning_rate, self.importance_weight_ph: batch_weights, } if hasattr(self, 'is_demo_ph'): feed_dict[self.is_demo_ph] = batch_is_demo # Do one gradient step # and optionally compute log for tensorboard if writer is not None: out = self.sess.run([self.summary] + self.step_ops + [self.value_target], feed_dict) summary = out.pop(0) writer.add_summary(summary, step) else: out = self.sess.run(self.step_ops + [self.value_target], feed_dict) # Unpack to monitor losses and entropy policy_loss, qf1_loss, qf2_loss, value_loss, *values = out entropy = values[4] # update priority here if self.priority_buffer: qf1 = values[0] value_target = values[-1] batch_rewards = np.reshape(batch_rewards, (self.batch_size, -1)) batch_dones = np.reshape(batch_dones, (self.batch_size, -1)) priorities = batch_rewards + (1 - batch_dones) * self.gamma * value_target - qf1 priorities = np.abs(priorities) + 1e-4 priorities = np.squeeze(priorities, axis=-1).tolist() if len(batch1_idxes): self.replay_buffer.update_priorities(batch1_idxes, priorities[:len(batch1_idxes)]) if len(batch2_idxes): self.augment_replay_buffer.update_priorities(batch2_idxes, priorities[-len(batch2_idxes):]) if self.log_ent_coef is not None: ent_coef_loss, ent_coef = values[-3:-1] return policy_loss, qf1_loss, qf2_loss, value_loss, entropy, demo_ratio, ent_coef_loss, ent_coef return policy_loss, qf1_loss, qf2_loss, value_loss, entropy, demo_ratio def learn(self, total_timesteps, callback=None, seed=None, log_interval=4, tb_log_name="SAC", reset_num_timesteps=True, replay_wrapper=None): new_tb_log = self._init_num_timesteps(reset_num_timesteps) if replay_wrapper is not None: self.replay_buffer = replay_wrapper(self.replay_buffer) self.augment_replay_buffer = replay_wrapper(self.augment_replay_buffer) if self.priority_buffer: self.replay_buffer.set_model(self) self.augment_replay_buffer.set_model(self) self.combined_replay_buffer = DoublePrioritizedReplayWrapper(self.replay_buffer.replay_buffer, self.augment_replay_buffer.replay_buffer) with SetVerbosity(self.verbose), TensorboardWriter(self.graph, self.tensorboard_log, tb_log_name, new_tb_log) \ as writer: self._setup_learn(seed) self.env_id = self.env.env.get_attr('spec')[0].id self.goal_dim = self.aug_env.get_attr('goal')[0].shape[0] self.obs_dim = self.aug_env.observation_space.shape[0] - 2 * self.goal_dim self.noise_mag = self.aug_env.get_attr('size_obstacle')[0][1] self.n_object = self.aug_env.get_attr('n_object')[0] self.reward_type = self.aug_env.get_attr('reward_type')[0] # Transform to callable if needed self.learning_rate = get_schedule_fn(self.learning_rate) # Initial learning rate current_lr = self.learning_rate(1) select_subgoal_time = 0. start_time = time.time() episode_rewards = [[0.0] for _ in range(self.env.env.num_envs)] episode_successes = [[] for _ in range(self.env.env.num_envs)] if self.action_noise is not None: self.action_noise.reset() self.episode_reward = np.zeros((1,)) ep_info_buf = deque(maxlen=100) pp_sr_buf = deque(maxlen=5) stack_sr_buf = deque(maxlen=5) n_updates = 0 start_decay = total_timesteps # TODO: should set task_array before reset if self.sequential and 'FetchStack' in self.env_id: current_max_nobject = 2 self.env.env.env_method('set_task_array', [[(2, 0), (2, 1), (1, 0)]] * self.env.env.num_envs) print('Set task_array to ', self.env.env.get_attr('task_array')[0]) self.env.env.env_method('set_random_ratio', [0.7] * self.env.env.num_envs) if 'FetchStack' in self.env_id and self.curriculum: self.start_augment_time = np.inf obs = self.env.reset() infos_values = [] self.ep_state_buf = [[] for _ in range(self.n_envs)] self.ep_transition_buf = [[] for _ in range(self.n_envs)] if 'FetchStack' in self.env_id: self.ep_current_nobject = [[] for _ in range(self.n_envs)] self.ep_selected_objects = [[] for _ in range(self.n_envs)] self.ep_task_mode = [[] for _ in range(self.n_envs)] self.ep_tower_height = [[] for _ in range(self.n_envs)] self.restart_steps = [] # Every element should be scalar self.subgoals = [] # Every element should be [*subgoals, ultimate goal] self.restart_states = [] # list of (n_candidate) states self.transition_storage = [] # every element is list of tuples. length of every element should match restart steps if 'FetchStack' in self.env_id: self.current_nobject = [] self.selected_objects = [] self.task_mode = [] # For filtering subgoals self.mean_value_buf = deque(maxlen=500) num_augment_ep_buf = deque(maxlen=100) num_success_augment_ep_buf = deque(maxlen=100) def convert_dict_to_obs(dict_obs): assert isinstance(dict_obs, dict) return np.concatenate([dict_obs[key] for key in ['observation', 'achieved_goal', 'desired_goal']]) def augment_cond(): if 'FetchStack' in self.env_id: if (not infos[idx]['is_success']) and task_modes[idx] == 1 and current_nobjects[idx] >= 2: return True return False elif 'MasspointMaze' in self.env_id or 'MasspointPushDoubleObstacle' in self.env_id : if not infos[idx]['is_success']: return True return False else: if (not infos[idx]['is_success']) and np.argmax(goal[3:]) == 0: return True return False def log_debug_value(value1, value2, goal_idx, is_success): if not os.path.exists(os.path.join(logger.get_dir(), 'debug_value.csv')): with open(os.path.join(logger.get_dir(), 'debug_value.csv'), 'a', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL) title = ['value1', 'value2', 'goal_idx', 'is_success', 'num_timesteps'] csvwriter.writerow(title) with open(os.path.join(logger.get_dir(), 'debug_value.csv'), 'a', newline='') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL) data = [value1, value2, goal_idx, int(is_success), self.num_timesteps] csvwriter.writerow(data) for step in range(total_timesteps): if callback is not None: # Only stop training if return value is False, not when it is None. This is for backwards # compatibility with callbacks that have no return statement. if callback(locals(), globals()) is False: break if self.curriculum and step % 3000 == 0: if 'FetchStack' in self.env.env.get_attr('spec')[0].id: # Stacking pp_sr = eval_model(self.eval_env, self, current_max_nobject if self.sequential else self.n_object, 1.0, init_on_table=(self.env.env.get_attr('spec')[0].id=='FetchStack-v2')) pp_sr_buf.append(pp_sr) stack_sr = eval_model(self.eval_env, self, current_max_nobject if self.sequential else self.n_object, 0.0, init_on_table=(self.env.env.get_attr('spec')[0].id=='FetchStack-v2')) stack_sr_buf.append(stack_sr) print('Pick-and-place success rate', np.mean(pp_sr_buf)) if self.sequential: if self.env.env.get_attr('random_ratio')[0] > 0.5 and np.mean(pp_sr_buf) > 0.8: _ratio = 0.3 # Force start augment after mastering pick-and-place on 2 objs if current_max_nobject == 2: self.start_augment_time = self.num_timesteps elif self.env.env.get_attr('random_ratio')[0] < 0.5 and current_max_nobject < self.n_object \ and np.mean(stack_sr_buf) > 1 / current_max_nobject: _ratio = 0.7 current_max_nobject += 1 previous_task_array = self.env.env.get_attr('task_array')[0] self.env.env.env_method('set_task_array', [ previous_task_array + [(current_max_nobject, j) for j in range(current_max_nobject)]] * self.env.env.num_envs) print('Set task_array to', self.env.env.get_attr('task_array')[0]) else: _ratio = self.env.env.get_attr('random_ratio')[0] else: if start_decay == total_timesteps and np.mean(pp_sr_buf) > 0.8: start_decay = step # Force start augment after mastering pick-and-place on env.n_object objs self.start_augment_time = self.num_timesteps _ratio = np.clip(0.7 - (step - start_decay) / 2e6, 0.3, 0.7) # from 0.7 to 0.3 elif 'FetchPushWallObstacle' in self.env_id: _ratio = max(1.0 - step / total_timesteps, 0.0) else: raise NotImplementedError self.env.env.env_method('set_random_ratio', [_ratio] * self.env.env.num_envs) print('Set random_ratio to', self.env.env.get_attr('random_ratio')[0]) # Before training starts, randomly sample actions # from a uniform distribution for better exploration. # Afterwards, use the learned policy # if random_exploration is set to 0 (normal setting) if (self.num_timesteps < self.learning_starts or np.random.rand() < self.random_exploration): # No need to rescale when sampling random action rescaled_action = np.stack([self.env.action_space.sample() for _ in range(self.env.env.num_envs)], axis=0) action = rescaled_action else: action = self.policy_tf.step(obs, deterministic=False) # Add noise to the action (improve exploration, # not needed in general) if self.action_noise is not None: action = np.clip(action + self.action_noise(), -1, 1) # Rescale from [-1, 1] to the correct bounds rescaled_action = action * np.abs(self.action_space.low) assert action.shape == (self.env.env.num_envs, ) + self.env.action_space.shape internal_states = self.env.env.env_method('get_state') if 'FetchStack' in self.env_id: current_nobjects = self.env.env.get_attr('current_nobject') selected_objects = self.env.env.get_attr('selected_objects') task_modes = self.env.env.get_attr('task_mode') tower_height = self.env.env.get_attr('tower_height') for i in range(self.n_envs): self.ep_state_buf[i].append(internal_states[i]) if 'FetchStack' in self.env_id: self.ep_current_nobject[i].append(current_nobjects[i]) self.ep_selected_objects[i].append(selected_objects[i]) self.ep_task_mode[i].append(task_modes[i]) self.ep_tower_height[i].append(tower_height[i]) new_obs, rewards, dones, infos = self.env.step(rescaled_action) next_obs = new_obs.copy() for i in range(self.n_envs): if dones[i]: next_obs[i] = self.env.convert_dict_to_obs(infos[i]['terminal_observation']) self.ep_transition_buf[i].append((obs[i], action[i], rewards[i], next_obs[i], dones[i])) # Store transition in the replay buffer. self.replay_buffer.add(obs, action, rewards, next_obs, dones) obs = new_obs for idx, _done in enumerate(dones): episode_rewards[idx][-1] += rewards[idx] if _done: episode_rewards[idx].append(0.0) maybe_is_success = infos[idx].get('is_success') if maybe_is_success is not None: episode_successes[idx].append(float(maybe_is_success)) # Retrieve reward and episode length if using Monitor wrapper for _info in infos: maybe_ep_info = _info.get('episode') if maybe_ep_info is not None: ep_info_buf.extend([maybe_ep_info]) if writer is not None: # Write reward per episode to tensorboard ep_reward = np.reshape(rewards, (self.env.env.num_envs, -1)) ep_done = np.reshape(dones, (self.env.env.num_envs, -1)) self.episode_reward = total_episode_reward_logger(self.episode_reward, ep_reward, ep_done, writer, self.num_timesteps) # episode augmentation for idx, done in enumerate(dones): if self.num_timesteps >= self.start_augment_time and done: goal = self.ep_transition_buf[idx][0][0][-self.goal_dim:] if augment_cond(): # Do augmentation # Sample start step and perturbation select_subgoal_time0 = time.time() _restart_steps, _subgoals = self.select_subgoal(self.ep_transition_buf[idx], k=self.n_subgoal, tower_height=self.ep_tower_height[idx] if 'FetchStack' in self.env_id else None) select_subgoal_time += (time.time() - select_subgoal_time0) # print('select subgoal time', select_subgoal_time) assert isinstance(_restart_steps, np.ndarray) assert isinstance(_subgoals, np.ndarray) for j in range(_restart_steps.shape[0]): self.restart_steps.append(_restart_steps[j]) self.subgoals.append([np.array(_subgoals[j]), goal.copy()]) assert len(self.subgoals[-1]) == 2 self.restart_states.append(self.ep_state_buf[idx][_restart_steps[j]]) self.transition_storage.append(self.ep_transition_buf[idx][:_restart_steps[j]]) if 'FetchStack' in self.env_id: self.current_nobject.append(self.ep_current_nobject[idx][0]) self.selected_objects.append(self.ep_selected_objects[idx][0]) self.task_mode.append(self.ep_task_mode[idx][0]) if done: self.ep_state_buf[idx] = [] self.ep_transition_buf[idx] = [] if 'FetchStack' in self.env_id: self.ep_current_nobject[idx] = [] self.ep_selected_objects[idx] = [] self.ep_task_mode[idx] = [] self.ep_tower_height[idx] = [] def switch_subgoal(switch_goal_flag, current_obs): for idx, flag in enumerate(switch_goal_flag): if flag: env_subgoals[idx].pop(0) # self.aug_env.set_attr('goal', env_subgoals[idx][0], indices=idx) self.aug_env.env_method('set_goal', [env_subgoals[idx][0]], indices=idx) if 'FetchStack' in self.env_id: # Use stack as ultimate task. assert self.task_mode[idx] == 1 self.aug_env.env_method('set_task_mode', [self.task_mode[idx]], indices=idx) switch_goal_flag[idx] = False current_obs[idx] = convert_dict_to_obs(self.aug_env.env_method('get_obs', indices=idx)[0]) while (len(self.restart_steps) >= self.aug_env.num_envs): # TODO Hard work here env_restart_steps = self.restart_steps[:self.aug_env.num_envs] env_subgoals = self.subgoals[:self.aug_env.num_envs] temp_subgoals = [goals[-2] for goals in env_subgoals].copy() ultimate_goals = [goals[-1] for goals in env_subgoals] env_storage = self.transition_storage[:self.aug_env.num_envs] env_increment_storage = [[] for _ in range(self.aug_env.num_envs)] self.aug_env.env_method('set_goal', [env_subgoals[idx][0] for idx in range(self.aug_env.num_envs)]) switch_goal_flag = [False for _ in range(self.aug_env.num_envs)] env_end_flag = [False for _ in range(self.aug_env.num_envs)] env_end_step = [np.inf for _ in range(self.aug_env.num_envs)] env_restart_state = self.restart_states[:self.aug_env.num_envs] self.aug_env.env_method('set_state', env_restart_state) if 'FetchStack' in self.env_id: self.aug_env.env_method('set_current_nobject', self.current_nobject[:self.aug_env.num_envs]) self.aug_env.env_method('set_selected_objects', self.selected_objects[:self.aug_env.num_envs]) # Use pick and place as sub-task self.aug_env.env_method('set_task_mode', np.zeros(self.aug_env.num_envs)) env_obs = self.aug_env.env_method('get_obs') env_obs = [convert_dict_to_obs(d) for d in env_obs] increment_step = 0 while not sum(env_end_flag) == self.aug_env.num_envs: # Switch subgoal according to switch_goal_flag, and update observation switch_subgoal(switch_goal_flag, env_obs) env_action, _ = self.predict(np.array(env_obs)) if 'FetchStack' in self.env_id: relabel_env_obs = self.aug_env.env_method('switch_obs_goal', env_obs, ultimate_goals, self.task_mode) else: relabel_env_obs = self.aug_env.env_method('switch_obs_goal', env_obs, ultimate_goals) clipped_actions = env_action # Clip the actions to avoid out of bound error if isinstance(self.aug_env.action_space, gym.spaces.Box): clipped_actions = np.clip(env_action, self.aug_env.action_space.low, self.aug_env.action_space.high) env_next_obs, _, _, env_info = self.aug_env.step(clipped_actions) self.num_aug_steps += (self.aug_env.num_envs - sum(env_end_flag)) if self.reward_type == 'sparse': temp_info = [None for _ in range(self.aug_env.num_envs)] else: temp_info = [{'previous_obs': env_obs[i]} for i in range(self.aug_env.num_envs)] if 'FetchStack' in self.env_id: _retask_env_next_obs = env_next_obs.copy() _retask_env_next_obs[:, self.obs_dim - 2:self.obs_dim] = 0 _retask_env_next_obs[:, self.obs_dim - 1] = 1 # Stack relabel_env_next_obs = self.aug_env.env_method('switch_obs_goal', env_next_obs, ultimate_goals, self.task_mode) env_reward = self.aug_env.env_method('compute_reward', _retask_env_next_obs, ultimate_goals, temp_info) if self.reward_type != "sparse": env_reward_and_success = self.aug_env.env_method('compute_reward_and_success', _retask_env_next_obs, ultimate_goals, temp_info) else: relabel_env_next_obs = self.aug_env.env_method('switch_obs_goal', env_next_obs, ultimate_goals) env_reward = self.aug_env.env_method('compute_reward', env_next_obs, ultimate_goals, temp_info) if self.reward_type != "sparse": env_reward_and_success = self.aug_env.env_method('compute_reward_and_success', env_next_obs, ultimate_goals, temp_info) for idx in range(self.aug_env.num_envs): # obs, act, reward, next_obs, done env_increment_storage[idx].append( (relabel_env_obs[idx], env_action[idx], env_reward[idx], relabel_env_next_obs[idx], False)) # if idx == 0: # print(increment_step, env_obs[idx][:9], env_next_obs[idx][:9], env_reward[idx]) env_obs = env_next_obs increment_step += 1 # print('increment step', increment_step) for idx, info in enumerate(env_info): # Special case, the agent succeeds the final goal half way if self.reward_type == 'sparse' and env_reward[idx] > 0 and env_end_flag[idx] is False: env_end_flag[idx] = True env_end_step[idx] = env_restart_steps[idx] + increment_step elif self.reward_type != 'sparse' and env_reward_and_success[idx][1] and env_end_flag[ idx] is False: env_end_flag[idx] = True env_end_step[idx] = env_restart_steps[idx] + increment_step # Exceed time limit if env_end_flag[idx] is False and env_restart_steps[idx] + increment_step \ > self.get_horizon(self.current_nobject[idx] if 'FetchStack' in self.env_id else None): env_end_flag[idx] = True # But env_end_step is still np.inf if info['is_success']: if len(env_subgoals[idx]) >= 2: switch_goal_flag[idx] = True # if idx == 0: # print('switch goal') elif env_end_flag[idx] == False: # this is the end env_end_flag[idx] = True env_end_step[idx] = env_restart_steps[idx] + increment_step else: pass if increment_step >= self.get_horizon(max(self.current_nobject[:self.aug_env.num_envs]) if 'FetchStack' in self.env_id else None) \ - min(env_restart_steps): break # print('end step', env_end_step) for idx, end_step in enumerate(env_end_step): if end_step <= self.get_horizon(self.current_nobject[idx] if 'FetchStack' in self.env_id else None): # log_debug_value(self.debug_value1[idx], self.debug_value2[idx], np.argmax(temp_subgoals[idx][3:]), True) # print(temp_subgoals[idx]) # is_self_aug = temp_subgoals[idx][3] transitions = env_increment_storage[idx][:end_step - env_restart_steps[idx]] for i in range(len(env_storage[idx])): if isinstance(self.augment_replay_buffer.replay_buffer, MultiWorkerReplayBuffer) \ or isinstance(self.augment_replay_buffer.replay_buffer, PrioritizedMultiWorkerReplayBuffer): self.augment_replay_buffer.add( *([np.expand_dims(item, axis=0) for item in env_storage[idx][i]])) else: self.augment_replay_buffer.add(*(env_storage[idx][i])) for i in range(len(transitions)): if i == len(transitions) - 1: temp = list(transitions[i]) temp[-1] = True transitions[i] = tuple(temp) if isinstance(self.augment_replay_buffer.replay_buffer, MultiWorkerReplayBuffer) \ or isinstance(self.augment_replay_buffer.replay_buffer, PrioritizedMultiWorkerReplayBuffer): self.augment_replay_buffer.add( *([np.expand_dims(item, axis=0) for item in transitions[i]])) else: self.augment_replay_buffer.add(*(transitions[i])) # else: # log_debug_value(self.debug_value1[idx], self.debug_value2[idx], np.argmax(temp_subgoals[idx][3:]), False) self.restart_steps = self.restart_steps[self.aug_env.num_envs:] self.subgoals = self.subgoals[self.aug_env.num_envs:] self.restart_states = self.restart_states[self.aug_env.num_envs:] self.transition_storage = self.transition_storage[self.aug_env.num_envs:] if 'FetchStack' in self.env_id: self.current_nobject = self.current_nobject[self.aug_env.num_envs:] self.selected_objects = self.selected_objects[self.aug_env.num_envs:] self.task_mode = self.task_mode[self.aug_env.num_envs:] if step % self.train_freq == 0: mb_infos_vals = [] # Update policy, critics and target networks for grad_step in range(self.gradient_steps): # Break if the warmup phase is not over # or if there are not enough samples in the replay buffer if not self.replay_buffer.can_sample(self.batch_size) \ or self.num_timesteps < self.learning_starts: break n_updates += 1 # Compute current learning_rate frac = 1.0 - step / total_timesteps current_lr = self.learning_rate(frac) # Update policy and critics (q functions) mb_infos_vals.append(self._train_step(step, writer, current_lr)) # Update target network if (step + grad_step) % self.target_update_interval == 0: # Update target network self.sess.run(self.target_update_op) # Log losses and entropy, useful for monitor training if len(mb_infos_vals) > 0: infos_values = np.mean(mb_infos_vals, axis=0) if len(episode_rewards[0][-101:-1]) == 0: mean_reward = -np.inf else: mean_reward = round(float( np.mean(np.concatenate([episode_rewards[i][-101:-1] for i in range(self.env.env.num_envs)]))), 1) num_episodes = sum([len(episode_rewards[i]) for i in range(len(episode_rewards))]) self.num_timesteps += self.env.env.num_envs # Display training infos if self.verbose >= 1 and dones[0] and log_interval is not None and len(episode_rewards[0]) % (log_interval // self.env.env.num_envs) == 0: fps = int(self.num_timesteps / (time.time() - start_time)) logger.logkv("episodes", num_episodes) logger.logkv("mean 100 episode reward", mean_reward) if len(ep_info_buf) > 0 and len(ep_info_buf[0]) > 0: logger.logkv('ep_rewmean', safe_mean([ep_info['r'] for ep_info in ep_info_buf])) logger.logkv('eplenmean', safe_mean([ep_info['l'] for ep_info in ep_info_buf])) logger.logkv("n_updates", n_updates) logger.logkv("current_lr", current_lr) logger.logkv("fps", fps) logger.logkv('time_elapsed', int(time.time() - start_time)) logger.logkv('select subgoal time', select_subgoal_time) if len(episode_successes[0]) > 0: logger.logkv("success rate", np.mean(np.concatenate([episode_successes[i][-100:] for i in range(self.env.env.num_envs)]))) if len(infos_values) > 0: for (name, val) in zip(self.infos_names, infos_values): logger.logkv(name, val) logger.logkv('augmented steps', len(self.augment_replay_buffer)) logger.logkv("original_timesteps", self.num_timesteps) logger.logkv("total timesteps", self.num_timesteps + self.num_aug_steps) logger.logkv("random_ratio", self.env.env.get_attr('random_ratio')[0]) logger.dumpkvs() # Reset infos: infos_values = [] return self def get_horizon(self, current_nobject): if 'FetchStack' in self.env_id and self.sequential: return max(current_nobject * 50, 100) return self.env.env.get_attr('spec')[0].max_episode_steps def select_subgoal(self, transition_buf, k, tower_height=None): if 'FetchStack' in self.env_id: assert tower_height is not None obs_buf, *_ = zip(*transition_buf) obs_buf = np.asarray(obs_buf) if 'FetchStack' in self.env_id and tower_height[-1] + 0.05 - obs_buf[-1][self.obs_dim + self.goal_dim + 2] > 0.01: # Tower height is equal to (or higher than) goal height. # print('towerheight exceed goalheight') return np.array([]), np.array([]) sample_t = np.random.randint(0, len(transition_buf), 4096) sample_obs = obs_buf[sample_t] noise = np.random.uniform(low=-self.noise_mag, high=self.noise_mag, size=(len(sample_t), 2)) sample_obs_buf = [] subgoal_obs_buf = [] filter_low = 0.5 filter_high = 1.0 if 'FetchPushWallobstacle' in self.env_id: filter_low = 0.7 filter_high = 0.9 if self.env.env.get_attr('random_ratio')[0] < 1 else 1.0 elif 'MasspointMaze' in self.env_id: filter_low = 0.7 filter_high = 0.9 if 'FetchStack' in self.env_id: ultimate_idx = np.argmax(sample_obs[0][self.obs_dim + self.goal_dim + 3:]) filter_subgoal = True sample_height = np.array(tower_height)[sample_t] for object_idx in range(0, self.n_object): if np.linalg.norm(sample_obs[0][3 + object_idx * 3: 3 + (object_idx + 1) * 3]) < 1e-3: # This object is masked continue obstacle_xy = sample_obs[:, 3 * (object_idx + 1):3 * (object_idx + 1) + 2] + noise # Find how many objects have been stacked obstacle_height = np.expand_dims(sample_height + 0.05, axis=1) # obstacle_height = max(sample_obs[0][self.obs_dim + self.goal_dim + 2] - 0.05, 0.425) * np.ones((len(sample_t), 1)) obstacle_xy = np.concatenate([obstacle_xy, obstacle_height], axis=-1) sample_obs[:, 3 * (object_idx + 1):3 * (object_idx + 1) + 3] = obstacle_xy sample_obs[:, 3 * (object_idx + 1 + self.n_object):3 * (object_idx + 1 + self.n_object) + 3] \ = sample_obs[:, 3 * (object_idx + 1):3 * (object_idx + 1) + 3] - sample_obs[:, 0:3] sample_obs[:, self.obs_dim:self.obs_dim + 3] = sample_obs[:, 3 * (ultimate_idx + 1):3 * (ultimate_idx + 1) + 3] sample_obs_buf.append(sample_obs.copy()) subgoal_obs = obs_buf[sample_t] # if debug: # subgoal_obs = np.tile(subgoal_obs, (2, 1)) subgoal_obs[:, self.obs_dim - 2: self.obs_dim] = np.array([1, 0]) # Pick and place subgoal_obs[:, self.obs_dim:self.obs_dim + 3] = subgoal_obs[:, 3 * (object_idx + 1):3 * (object_idx + 1) + 3] one_hot = np.zeros(self.n_object) one_hot[object_idx] = 1 subgoal_obs[:, self.obs_dim + 3:self.obs_dim + self.goal_dim] = one_hot subgoal_obs[:, self.obs_dim + self.goal_dim:self.obs_dim + self.goal_dim + 3] = obstacle_xy # subgoal_obs[:, self.obs_dim + self.goal_dim + 2:self.obs_dim + self.goal_dim + 3] = subgoal_obs[:, 3 * ( # object_idx + 1) + 2:3 * (object_idx + 1) + 3] subgoal_obs[:, self.obs_dim + self.goal_dim + 3:self.obs_dim + self.goal_dim * 2] = one_hot subgoal_obs_buf.append(subgoal_obs) elif 'MasspointMaze' in self.env_id: filter_subgoal = True ego_xy = sample_obs[:, 0:2] + noise # Path 2 sample_obs[:, 0: 2] = ego_xy sample_obs[:, self.obs_dim: self.obs_dim + 2] = ego_xy sample_obs_buf.append(sample_obs.copy()) # Path 1 subgoal_obs = obs_buf[sample_t] subgoal_obs[:, self.obs_dim:self.obs_dim + 3] = subgoal_obs[:, 0:3] subgoal_obs[:, self.obs_dim + self.goal_dim:self.obs_dim + self.goal_dim + 2] = ego_xy if self.env_id != 'MasspointMaze-v3': subgoal_obs[:, self.obs_dim + self.goal_dim + 2:self.obs_dim + self.goal_dim + 3] = subgoal_obs[:, 2:3] subgoal_obs_buf.append(subgoal_obs) else: ultimate_idx = np.argmax(sample_obs[0][self.obs_dim + self.goal_dim + 3:]) filter_subgoal = True for object_idx in range(self.n_object): # Also search self position obstacle_xy = sample_obs[:, 3 * (object_idx+1):3*(object_idx+1) + 2] + noise # Path2 if object_idx == self.n_object - 1 and self.env_id is 'MasspointPushDoubleObstacle-v2': sample_obs[0: 2] = obstacle_xy sample_obs[:, 3*(object_idx+1):3*(object_idx+1)+2] = obstacle_xy sample_obs[:, 3*(object_idx+1+self.n_object):3*(object_idx+1+self.n_object)+2] \ = sample_obs[:, 3*(object_idx+1):3*(object_idx+1)+2] - sample_obs[:, 0:2] # achieved_goal sample_obs[:, self.obs_dim:self.obs_dim + 3] \ = sample_obs[:, 3 * (ultimate_idx + 1):3 * (ultimate_idx + 1) + 3] sample_obs_buf.append(sample_obs.copy()) # Path1 subgoal_obs = obs_buf[sample_t] # achieved_goal subgoal_obs[:, self.obs_dim:self.obs_dim+3] = subgoal_obs[:, 3*(object_idx+1):3*(object_idx+1)+3] one_hot = np.zeros(self.n_object) one_hot[object_idx] = 1 subgoal_obs[:, self.obs_dim+3:self.obs_dim+self.goal_dim] = one_hot # desired_goal subgoal_obs[:, self.obs_dim+self.goal_dim:self.obs_dim+self.goal_dim+2] = obstacle_xy subgoal_obs[:, self.obs_dim+self.goal_dim+2:self.obs_dim+self.goal_dim+3] \ = subgoal_obs[:, 3*(object_idx+1)+2:3*(object_idx+1)+3] subgoal_obs[:, self.obs_dim+self.goal_dim+3:self.obs_dim+self.goal_dim*2] = one_hot subgoal_obs_buf.append(subgoal_obs) # print(len(sample_obs_buf)) if len(sample_obs_buf) == 0: return np.array([]), np.array([]) sample_obs_buf = np.concatenate(sample_obs_buf, axis=0) # value2 = self.model.value(sample_obs_buf) subgoal_obs_buf = np.concatenate(subgoal_obs_buf) # value1 = self.model.value(subgoal_obs_buf) # _values = self.model.value(np.concatenate([sample_obs_buf, subgoal_obs_buf], axis=0)) feed_dict = {self.observations_ph: np.concatenate([sample_obs_buf, subgoal_obs_buf], axis=0)} _values = np.squeeze(self.sess.run(self.step_ops[6], feed_dict), axis=-1) value2 = _values[:sample_obs_buf.shape[0]] value1 = _values[sample_obs_buf.shape[0]:] normalize_value1 = (value1 - np.min(value1)) / (np.max(value1) - np.min(value1)) normalize_value2 = (value2 - np.min(value2)) / (np.max(value2) - np.min(value2)) # best_idx = np.argmax(normalize_value1 * normalize_value2) ind = np.argsort(normalize_value1 * normalize_value2) good_ind = ind[-k:] if filter_subgoal: mean_values = (value1[good_ind] + value2[good_ind]) / 2 # print(mean_values) assert mean_values.shape[0] == k # Filter by hard threshold # In the beginning, the value fn tends to over estimate filtered_idx = np.where(np.logical_and(mean_values < filter_high, mean_values > filter_low))[0] good_ind = good_ind[filtered_idx] restart_step = sample_t[good_ind % len(sample_t)] subgoal = subgoal_obs_buf[good_ind, self.obs_dim + self.goal_dim:self.obs_dim + self.goal_dim * 2] return restart_step, subgoal def logpac(self, action): from stable_baselines.sac.policies import gaussian_likelihood, EPS act_mu = self.policy_tf.act_mu log_std = tf.log(self.policy_tf.std) # Potentially we need to clip atanh and pass gradient log_u = gaussian_likelihood(tf.atanh(tf.clip_by_value(action, -0.99, 0.99)), act_mu, log_std) log_ac = log_u - tf.reduce_sum(tf.log(1 - action ** 2 + EPS), axis=1) return log_ac def action_probability(self, observation, state=None, mask=None, actions=None, logp=False): if actions is not None: raise ValueError("Error: SAC does not have action probabilities.") warnings.warn("Even though SAC has a Gaussian policy, it cannot return a distribution as it " "is squashed by a tanh before being scaled and ouputed.") return None def predict(self, observation, state=None, mask=None, deterministic=True): observation = np.array(observation) vectorized_env = self._is_vectorized_observation(observation, self.observation_space) observation = observation.reshape((-1,) + self.observation_space.shape) actions = self.policy_tf.step(observation, deterministic=deterministic) actions = actions.reshape((-1,) + self.action_space.shape) # reshape to the correct action shape actions = actions * np.abs(self.action_space.low) # scale the output for the prediction if not vectorized_env: actions = actions[0] return actions, None def get_parameter_list(self): return (self.params + self.target_params) def save(self, save_path, cloudpickle=False): data = { "learning_rate": self.learning_rate, "buffer_size": self.buffer_size, "learning_starts": self.learning_starts, "train_freq": self.train_freq, "batch_size": self.batch_size, "tau": self.tau, "ent_coef": self.ent_coef if isinstance(self.ent_coef, float) else 'auto', "target_entropy": self.target_entropy, # Should we also store the replay buffer? # this may lead to high memory usage # with all transition inside # "replay_buffer": self.replay_buffer "gamma": self.gamma, "verbose": self.verbose, "observation_space": self.observation_space, "action_space": self.action_space, "policy": self.policy, "n_envs": self.n_envs, "action_noise": self.action_noise, "random_exploration": self.random_exploration, "_vectorize_action": self._vectorize_action, "policy_kwargs": self.policy_kwargs } params_to_save = self.get_parameters() self._save_to_file(save_path, data=data, params=params_to_save, cloudpickle=cloudpickle)
[]
2024-01-10
IrisLi17/self-imitation-via-reduction
baselines~sac_parallel~sac_parallel.py
import sys import time import multiprocessing from collections import deque import warnings import numpy as np import tensorflow as tf from stable_baselines.a2c.utils import total_episode_reward_logger from stable_baselines.common import tf_util, OffPolicyRLModel, SetVerbosity, TensorboardWriter from stable_baselines.common.vec_env import VecEnv from utils.replay_buffer import MultiWorkerReplayBuffer, PrioritizedMultiWorkerReplayBuffer from stable_baselines.ppo2.ppo2 import safe_mean, get_schedule_fn from stable_baselines.sac.policies import SACPolicy from stable_baselines import logger from utils.eval_stack import eval_model def get_vars(scope): """ Alias for get_trainable_vars :param scope: (str) :return: [tf Variable] """ return tf_util.get_trainable_vars(scope) class SAC_parallel(OffPolicyRLModel): """ Soft Actor-Critic (SAC) Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor, This implementation borrows code from original implementation (https://github.com/haarnoja/sac) from OpenAI Spinning Up (https://github.com/openai/spinningup) and from the Softlearning repo (https://github.com/rail-berkeley/softlearning/) Paper: https://arxiv.org/abs/1801.01290 Introduction to SAC: https://spinningup.openai.com/en/latest/algorithms/sac.html :param policy: (SACPolicy or str) The policy model to use (MlpPolicy, CnnPolicy, LnMlpPolicy, ...) :param env: (Gym environment or str) The environment to learn from (if registered in Gym, can be str) :param gamma: (float) the discount factor :param learning_rate: (float or callable) learning rate for adam optimizer, the same learning rate will be used for all networks (Q-Values, Actor and Value function) it can be a function of the current progress (from 1 to 0) :param buffer_size: (int) size of the replay buffer :param batch_size: (int) Minibatch size for each gradient update :param tau: (float) the soft update coefficient ("polyak update", between 0 and 1) :param ent_coef: (str or float) Entropy regularization coefficient. (Equivalent to inverse of reward scale in the original SAC paper.) Controlling exploration/exploitation trade-off. Set it to 'auto' to learn it automatically (and 'auto_0.1' for using 0.1 as initial value) :param train_freq: (int) Update the model every `train_freq` steps. :param learning_starts: (int) how many steps of the model to collect transitions for before learning starts :param target_update_interval: (int) update the target network every `target_network_update_freq` steps. :param gradient_steps: (int) How many gradient update after each step :param target_entropy: (str or float) target entropy when learning ent_coef (ent_coef = 'auto') :param action_noise: (ActionNoise) the action noise type (None by default), this can help for hard exploration problem. Cf DDPG for the different action noise type. :param random_exploration: (float) Probability of taking a random action (as in an epsilon-greedy strategy) This is not needed for SAC normally but can help exploring when using HER + SAC. This hack was present in the original OpenAI Baselines repo (DDPG + HER) :param verbose: (int) the verbosity level: 0 none, 1 training information, 2 tensorflow debug :param tensorboard_log: (str) the log location for tensorboard (if None, no logging) :param _init_setup_model: (bool) Whether or not to build the network at the creation of the instance :param policy_kwargs: (dict) additional arguments to be passed to the policy on creation :param full_tensorboard_log: (bool) enable additional logging when using tensorboard Note: this has no effect on SAC logging for now """ def __init__(self, policy, env, gamma=0.99, learning_rate=3e-4, buffer_size=50000, priority_buffer=False, alpha=0.6, learning_starts=100, train_freq=1, batch_size=64, tau=0.005, ent_coef='auto', target_update_interval=1, gradient_steps=1, target_entropy='auto', action_noise=None, eval_env=None, curriculum=False, sequential=False, sil=False, sil_coef=1.0, random_exploration=0.0, verbose=0, tensorboard_log=None, _init_setup_model=True, policy_kwargs=None, full_tensorboard_log=False): super(SAC_parallel, self).__init__(policy=policy, env=env, replay_buffer=None, verbose=verbose, policy_base=SACPolicy, requires_vec_env=False, policy_kwargs=policy_kwargs) self.buffer_size = buffer_size self.priority_buffer = priority_buffer self.alpha = alpha self.learning_rate = learning_rate self.learning_starts = learning_starts self.train_freq = train_freq self.batch_size = batch_size self.tau = tau # In the original paper, same learning rate is used for all networks # self.policy_lr = learning_rate # self.qf_lr = learning_rate # self.vf_lr = learning_rate # Entropy coefficient / Entropy temperature # Inverse of the reward scale self.ent_coef = ent_coef self.target_update_interval = target_update_interval self.gradient_steps = gradient_steps self.gamma = gamma self.action_noise = action_noise self.random_exploration = random_exploration self.eval_env = eval_env self.curriculum = curriculum self.sequential = sequential self.sil = sil self.sil_coef = sil_coef self.value_fn = None self.graph = None self.replay_buffer = None self.episode_reward = None self.sess = None self.tensorboard_log = tensorboard_log self.verbose = verbose self.params = None self.summary = None self.policy_tf = None self.target_entropy = target_entropy self.full_tensorboard_log = full_tensorboard_log self.obs_target = None self.target_policy = None self.actions_ph = None self.rewards_ph = None self.terminals_ph = None self.observations_ph = None self.action_target = None self.next_observations_ph = None self.value_target = None self.step_ops = None self.target_update_op = None self.infos_names = None self.entropy = None self.target_params = None self.learning_rate_ph = None self.processed_obs_ph = None self.processed_next_obs_ph = None self.log_ent_coef = None self.logpac_op = None if _init_setup_model: self.setup_model() def _get_pretrain_placeholders(self): policy = self.policy_tf # Rescale deterministic_action = self.deterministic_action * np.abs(self.action_space.low) return policy.obs_ph, self.actions_ph, deterministic_action def setup_model(self): with SetVerbosity(self.verbose): self.graph = tf.Graph() with self.graph.as_default(): n_cpu = multiprocessing.cpu_count() if sys.platform == 'darwin': n_cpu //= 2 self.sess = tf_util.make_session(num_cpu=n_cpu, graph=self.graph) if hasattr(self.env, "env") and isinstance(self.env.env, VecEnv): self.n_envs = self.env.env.num_envs else: self.n_envs = 1 if self.priority_buffer: self.replay_buffer = PrioritizedMultiWorkerReplayBuffer(self.buffer_size, self.alpha, num_workers=self.env.env.num_envs, gamma=self.gamma) else: self.replay_buffer = MultiWorkerReplayBuffer(self.buffer_size, num_workers=self.n_envs, gamma=self.gamma) with tf.variable_scope("input", reuse=False): # Create policy and target TF objects self.policy_tf = self.policy(self.sess, self.observation_space, self.action_space, **self.policy_kwargs) self.target_policy = self.policy(self.sess, self.observation_space, self.action_space, **self.policy_kwargs) # Initialize Placeholders self.observations_ph = self.policy_tf.obs_ph # Normalized observation for pixels self.processed_obs_ph = self.policy_tf.processed_obs self.next_observations_ph = self.target_policy.obs_ph self.processed_next_obs_ph = self.target_policy.processed_obs self.action_target = self.target_policy.action_ph self.terminals_ph = tf.placeholder(tf.float32, shape=(None, 1), name='terminals') self.rewards_ph = tf.placeholder(tf.float32, shape=(None, 1), name='rewards') self.actions_ph = tf.placeholder(tf.float32, shape=(None,) + self.action_space.shape, name='actions') self.learning_rate_ph = tf.placeholder(tf.float32, [], name="learning_rate_ph") self.importance_weight_ph = tf.placeholder(tf.float32, shape=(None,), name='weights') # self.sum_rs_ph = tf.placeholder(tf.float32, shape=(None, 1), name="sum_rs") with tf.variable_scope("model", reuse=False): # Create the policy # first return value corresponds to deterministic actions # policy_out corresponds to stochastic actions, used for training # logp_pi is the log probabilty of actions taken by the policy self.deterministic_action, policy_out, logp_pi = self.policy_tf.make_actor(self.processed_obs_ph) # Monitor the entropy of the policy, # this is not used for training self.entropy = tf.reduce_mean(self.policy_tf.entropy) # Use two Q-functions to improve performance by reducing overestimation bias. qf1, qf2, value_fn = self.policy_tf.make_critics(self.processed_obs_ph, self.actions_ph, create_qf=True, create_vf=True) qf1_pi, qf2_pi, _ = self.policy_tf.make_critics(self.processed_obs_ph, policy_out, create_qf=True, create_vf=False, reuse=True) # Target entropy is used when learning the entropy coefficient if self.target_entropy == 'auto': # automatically set target entropy if needed self.target_entropy = -np.prod(self.env.action_space.shape).astype(np.float32) else: # Force conversion # this will also throw an error for unexpected string self.target_entropy = float(self.target_entropy) # The entropy coefficient or entropy can be learned automatically # see Automating Entropy Adjustment for Maximum Entropy RL section # of https://arxiv.org/abs/1812.05905 if isinstance(self.ent_coef, str) and self.ent_coef.startswith('auto'): # Default initial value of ent_coef when learned init_value = 1.0 if '_' in self.ent_coef: init_value = float(self.ent_coef.split('_')[1]) assert init_value > 0., "The initial value of ent_coef must be greater than 0" self.log_ent_coef = tf.get_variable('log_ent_coef', dtype=tf.float32, initializer=np.log(init_value).astype(np.float32)) self.ent_coef = tf.exp(self.log_ent_coef) else: # Force conversion to float # this will throw an error if a malformed string (different from 'auto') # is passed self.ent_coef = float(self.ent_coef) with tf.variable_scope("target", reuse=False): # Create the value network _, _, value_target = self.target_policy.make_critics(self.processed_next_obs_ph, create_qf=False, create_vf=True) self.value_target = value_target with tf.variable_scope("loss", reuse=False): # Take the min of the two Q-Values (Double-Q Learning) min_qf_pi = tf.minimum(qf1_pi, qf2_pi) # Target for Q value regression q_backup = tf.stop_gradient( self.rewards_ph + (1 - self.terminals_ph) * self.gamma * self.value_target ) # Compute Q-Function loss # TODO: test with huber loss (it would avoid too high values) qf1_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (q_backup - qf1) ** 2) qf2_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (q_backup - qf2) ** 2) # Compute the entropy temperature loss # it is used when the entropy coefficient is learned ent_coef_loss, entropy_optimizer = None, None if not isinstance(self.ent_coef, float): ent_coef_loss = -tf.reduce_mean( self.log_ent_coef * tf.stop_gradient(logp_pi + self.target_entropy)) entropy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) # Compute the policy loss # Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi) policy_kl_loss = tf.reduce_mean(self.ent_coef * logp_pi - qf1_pi) # Add optional SIL loss if self.sil: self.logpac_op = logp_ac = self.logpac(self.actions_ph) policy_kl_loss += self.sil_coef * tf.reduce_mean( -logp_ac * tf.stop_gradient(tf.nn.relu(qf1 - value_fn))) # NOTE: in the original implementation, they have an additional # regularization loss for the gaussian parameters # this is not used for now # policy_loss = (policy_kl_loss + policy_regularization_loss) policy_loss = policy_kl_loss # Target for value fn regression # We update the vf towards the min of two Q-functions in order to # reduce overestimation bias from function approximation error. v_backup = tf.stop_gradient(min_qf_pi - self.ent_coef * logp_pi) value_loss = 0.5 * tf.reduce_mean(self.importance_weight_ph * (value_fn - v_backup) ** 2) values_losses = qf1_loss + qf2_loss + value_loss # Policy train op # (has to be separate from value train op, because min_qf_pi appears in policy_loss) policy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) policy_train_op = policy_optimizer.minimize(policy_loss, var_list=get_vars('model/pi')) # Value train op value_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) values_params = get_vars('model/values_fn') source_params = get_vars("model/values_fn/vf") target_params = get_vars("target/values_fn/vf") # Polyak averaging for target variables self.target_update_op = [ tf.assign(target, (1 - self.tau) * target + self.tau * source) for target, source in zip(target_params, source_params) ] # Initializing target to match source variables target_init_op = [ tf.assign(target, source) for target, source in zip(target_params, source_params) ] # Control flow is used because sess.run otherwise evaluates in nondeterministic order # and we first need to compute the policy action before computing q values losses with tf.control_dependencies([policy_train_op]): train_values_op = value_optimizer.minimize(values_losses, var_list=values_params) self.infos_names = ['policy_loss', 'qf1_loss', 'qf2_loss', 'value_loss', 'entropy'] # All ops to call during one training step self.step_ops = [policy_loss, qf1_loss, qf2_loss, value_loss, qf1, qf2, value_fn, logp_pi, self.entropy, policy_train_op, train_values_op] # Add entropy coefficient optimization operation if needed if ent_coef_loss is not None: with tf.control_dependencies([train_values_op]): ent_coef_op = entropy_optimizer.minimize(ent_coef_loss, var_list=self.log_ent_coef) self.infos_names += ['ent_coef_loss', 'ent_coef'] self.step_ops += [ent_coef_op, ent_coef_loss, self.ent_coef] # Monitor losses and entropy in tensorboard tf.summary.scalar('policy_loss', policy_loss) tf.summary.scalar('qf1_loss', qf1_loss) tf.summary.scalar('qf2_loss', qf2_loss) tf.summary.scalar('value_loss', value_loss) tf.summary.scalar('entropy', self.entropy) if ent_coef_loss is not None: tf.summary.scalar('ent_coef_loss', ent_coef_loss) tf.summary.scalar('ent_coef', self.ent_coef) tf.summary.scalar('learning_rate', tf.reduce_mean(self.learning_rate_ph)) # Retrieve parameters that must be saved self.params = get_vars("model") self.target_params = get_vars("target/values_fn/vf") # Initialize Variables and target network with self.sess.as_default(): self.sess.run(tf.global_variables_initializer()) self.sess.run(target_init_op) self.summary = tf.summary.merge_all() def _train_step(self, step, writer, learning_rate): # Sample a batch from the replay buffer if self.priority_buffer: batch = self.replay_buffer.sample(self.batch_size, beta=0.4) batch_obs, batch_actions, batch_rewards, batch_next_obs, batch_dones, weights, idxes = batch else: batch = self.replay_buffer.sample(self.batch_size) batch_obs, batch_actions, batch_rewards, batch_next_obs, batch_dones = batch weights = np.ones(batch_obs.shape[0]) feed_dict = { self.observations_ph: batch_obs, self.actions_ph: batch_actions, self.next_observations_ph: batch_next_obs, self.rewards_ph: batch_rewards.reshape(self.batch_size, -1), self.terminals_ph: batch_dones.reshape(self.batch_size, -1), self.learning_rate_ph: learning_rate, self.importance_weight_ph: weights, } # Do one gradient step # and optionally compute log for tensorboard if writer is not None: out = self.sess.run([self.summary] + self.step_ops + [self.value_target], feed_dict) summary = out.pop(0) writer.add_summary(summary, step) else: out = self.sess.run(self.step_ops + [self.value_target], feed_dict) # Unpack to monitor losses and entropy policy_loss, qf1_loss, qf2_loss, value_loss, *values = out entropy = values[4] # Update priority if self.priority_buffer: qf1 = values[0] value_target = values[-1] batch_rewards = np.reshape(batch_rewards, (self.batch_size, -1)) batch_dones = np.reshape(batch_dones, (self.batch_size, -1)) priorities = batch_rewards + (1 - batch_dones) * self.gamma * value_target - qf1 priorities = np.abs(priorities) + 1e-4 priorities = np.squeeze(priorities, axis=-1).tolist() self.replay_buffer.update_priorities(idxes, priorities) if self.log_ent_coef is not None: ent_coef_loss, ent_coef = values[-3:-1] return policy_loss, qf1_loss, qf2_loss, value_loss, entropy, ent_coef_loss, ent_coef return policy_loss, qf1_loss, qf2_loss, value_loss, entropy def learn(self, total_timesteps, callback=None, seed=None, log_interval=4, tb_log_name="SAC", reset_num_timesteps=True, replay_wrapper=None): new_tb_log = self._init_num_timesteps(reset_num_timesteps) if replay_wrapper is not None: self.replay_buffer = replay_wrapper(self.replay_buffer) if self.priority_buffer: self.replay_buffer.set_model(self) with SetVerbosity(self.verbose), TensorboardWriter(self.graph, self.tensorboard_log, tb_log_name, new_tb_log) \ as writer: self._setup_learn(seed) self.env_id = self.env.env.get_attr('spec')[0].id # Transform to callable if needed self.learning_rate = get_schedule_fn(self.learning_rate) # Initial learning rate current_lr = self.learning_rate(1) start_time = time.time() store_time = 0.0 step_time = 0.0 train_time = 0.0 episode_rewards = [[0.0] for _ in range(self.env.env.num_envs)] episode_successes = [[] for _ in range(self.env.env.num_envs)] if self.action_noise is not None: self.action_noise.reset() assert isinstance(self.env.env, VecEnv) self.episode_reward = np.zeros((1,)) ep_info_buf = deque(maxlen=100) n_updates = 0 infos_values = [] pp_sr_buf = deque(maxlen=5) stack_sr_buf = deque(maxlen=5) start_decay = total_timesteps if self.sequential and 'FetchStack' in self.env_id: current_max_nobject = 2 self.env.env.env_method('set_task_array', [[(2, 0), (2, 1), (1, 0)]] * self.env.env.num_envs) print('Set task_array to ', self.env.env.get_attr('task_array')[0]) self.env.env.env_method('set_random_ratio', [0.7] * self.env.env.num_envs) obs = self.env.reset() print(obs.shape) for step in range(total_timesteps): if callback is not None: # Only stop training if return value is False, not when it is None. This is for backwards # compatibility with callbacks that have no return statement. if callback(locals(), globals()) is False: break if self.curriculum and step % 3000 == 0: if 'FetchStack' in self.env.env.get_attr('spec')[0].id: # Stacking pp_sr = eval_model(self.eval_env, self, current_max_nobject if self.sequential else self.env.env.get_attr('n_object')[0], 1.0, init_on_table=(self.env.env.get_attr('spec')[0].id == 'FetchStack-v2')) pp_sr_buf.append(pp_sr) stack_sr = eval_model(self.eval_env, self, current_max_nobject if self.sequential else self.env.env.get_attr('n_object')[0], 0.0, init_on_table=(self.env.env.get_attr('spec')[0].id == 'FetchStack-v2')) stack_sr_buf.append(stack_sr) print('Pick-and-place success rate', np.mean(pp_sr_buf)) if self.sequential: if self.env.env.get_attr('random_ratio')[0] > 0.5 and np.mean(pp_sr_buf) > 0.8: _ratio = 0.3 elif self.env.env.get_attr('random_ratio')[0] < 0.5 \ and current_max_nobject < self.env.env.get_attr('n_object')[0] \ and np.mean(stack_sr_buf) > 1 / current_max_nobject: _ratio = 0.7 current_max_nobject += 1 previous_task_array = self.env.env.get_attr('task_array')[0] self.env.env.env_method('set_task_array', [ previous_task_array + [(current_max_nobject, j) for j in range(current_max_nobject)]] * self.env.env.num_envs) print('Set task_array to', self.env.env.get_attr('task_array')[0]) else: _ratio = self.env.env.get_attr('random_ratio')[0] else: if start_decay == total_timesteps and np.mean(pp_sr_buf) > 0.8: start_decay = step _ratio = np.clip(0.7 - (step - start_decay) / 2e6, 0.3, 0.7) # from 0.7 to 0.3 elif 'FetchPushWallObstacle' in self.env_id: _ratio = max(1.0 - step / total_timesteps, 0.0) else: raise NotImplementedError self.env.env.env_method('set_random_ratio', [_ratio] * self.env.env.num_envs) print('Set random_ratio to', self.env.env.get_attr('random_ratio')[0]) # Before training starts, randomly sample actions # from a uniform distribution for better exploration. # Afterwards, use the learned policy # if random_exploration is set to 0 (normal setting) if (self.num_timesteps < self.learning_starts or np.random.rand() < self.random_exploration): rescaled_action = np.stack([self.env.action_space.sample() for _ in range(self.env.env.num_envs)], axis=0) action = rescaled_action else: action = self.policy_tf.step(obs, deterministic=False) # Add noise to the action (improve exploration, # not needed in general) if self.action_noise is not None: action = np.clip(action + self.action_noise(), -1, 1) # Rescale from [-1, 1] to the correct bounds rescaled_action = action * np.abs(self.action_space.low) assert action.shape == (self.env.env.num_envs, ) + self.env.action_space.shape step_time0 = time.time() new_obs, reward, done, info = self.env.step(rescaled_action) step_time += time.time() - step_time0 next_obs = new_obs.copy() for idx, _done in enumerate(done): if _done: next_obs[idx] = self.env.convert_dict_to_obs(info[idx]['terminal_observation']) # Store transition in the replay buffer. store_time0 = time.time() self.replay_buffer.add(obs, action, reward, next_obs, done) store_time += time.time() - store_time0 obs = new_obs for idx, _done in enumerate(done): episode_rewards[idx][-1] += reward[idx] if _done: episode_rewards[idx].append(0.0) maybe_is_success = info[idx].get('is_success') if maybe_is_success is not None: episode_successes[idx].append(float(maybe_is_success)) # Retrieve reward and episode length if using Monitor wrapper for _info in info: maybe_ep_info = _info.get('episode') if maybe_ep_info is not None: ep_info_buf.extend([maybe_ep_info]) if writer is not None: # Write reward per episode to tensorboard ep_reward = np.reshape(reward, (self.env.env.num_envs, -1)) ep_done = np.reshape(done, (self.env.env.num_envs, -1)) self.episode_reward = total_episode_reward_logger(self.episode_reward, ep_reward, ep_done, writer, self.num_timesteps) train_time0 = time.time() if step % self.train_freq == 0: mb_infos_vals = [] # Update policy, critics and target networks for grad_step in range(self.gradient_steps): # Break if the warmup phase is not over # or if there are not enough samples in the replay buffer if not self.replay_buffer.can_sample(self.batch_size) \ or self.num_timesteps < self.learning_starts: break n_updates += 1 # Compute current learning_rate frac = 1.0 - step / total_timesteps current_lr = self.learning_rate(frac) # Update policy and critics (q functions) mb_infos_vals.append(self._train_step(step, writer, current_lr)) # Update target network if (step + grad_step) % self.target_update_interval == 0: # Update target network self.sess.run(self.target_update_op) # Log losses and entropy, useful for monitor training if len(mb_infos_vals) > 0: infos_values = np.mean(mb_infos_vals, axis=0) train_time += time.time() - train_time0 if len(episode_rewards[0][-101:-1]) == 0: mean_reward = -np.inf else: mean_reward = round(float(np.mean(np.concatenate([episode_rewards[i][-101:-1] for i in range(self.env.env.num_envs)]))), 1) num_episodes = sum([len(episode_rewards[i]) for i in range(len(episode_rewards))]) self.num_timesteps += self.env.env.num_envs # Display training infos if self.verbose >= 1 and done[0] and log_interval is not None and len(episode_rewards[0]) % (log_interval // self.env.env.num_envs) == 0: fps = int(self.num_timesteps / (time.time() - start_time)) logger.logkv("episodes", num_episodes) logger.logkv("mean 100 episode reward", mean_reward) if len(ep_info_buf) > 0 and len(ep_info_buf[0]) > 0: logger.logkv('ep_rewmean', safe_mean([ep_info['r'] for ep_info in ep_info_buf])) logger.logkv('eplenmean', safe_mean([ep_info['l'] for ep_info in ep_info_buf])) logger.logkv("n_updates", n_updates) logger.logkv("current_lr", current_lr) logger.logkv("fps", fps) logger.logkv('time_elapsed', int(time.time() - start_time)) if len(episode_successes[0]) > 0: logger.logkv("success rate", np.mean(np.concatenate([episode_successes[i][-100:] for i in range(self.env.env.num_envs)]))) if len(infos_values) > 0: for (name, val) in zip(self.infos_names, infos_values): logger.logkv(name, val) logger.logkv("total timesteps", self.num_timesteps) if hasattr(self.eval_env.unwrapped, 'random_ratio'): logger.logkv("random_ratio", self.env.env.get_attr('random_ratio')[0]) logger.dumpkvs() # Reset infos: infos_values = [] return self def logpac(self, action): from stable_baselines.sac.policies import gaussian_likelihood, EPS act_mu = self.policy_tf.act_mu log_std = tf.log(self.policy_tf.std) # Potentially we need to clip atanh and pass gradient log_u = gaussian_likelihood(tf.atanh(tf.clip_by_value(action, -0.99, 0.99)), act_mu, log_std) log_ac = log_u - tf.reduce_sum(tf.log(1 - action ** 2 + EPS), axis=1) return log_ac def action_probability(self, observation, state=None, mask=None, actions=None, logp=False): if actions is not None: raise ValueError("Error: SAC does not have action probabilities.") warnings.warn("Even though SAC has a Gaussian policy, it cannot return a distribution as it " "is squashed by a tanh before being scaled and ouputed.") return None def predict(self, observation, state=None, mask=None, deterministic=True): observation = np.array(observation) vectorized_env = self._is_vectorized_observation(observation, self.observation_space) observation = observation.reshape((-1,) + self.observation_space.shape) actions = self.policy_tf.step(observation, deterministic=deterministic) actions = actions.reshape((-1,) + self.action_space.shape) # reshape to the correct action shape actions = actions * np.abs(self.action_space.low) # scale the output for the prediction if not vectorized_env: actions = actions[0] return actions, None def get_parameter_list(self): return (self.params + self.target_params) def save(self, save_path, cloudpickle=False): data = { "learning_rate": self.learning_rate, "buffer_size": self.buffer_size, "learning_starts": self.learning_starts, "train_freq": self.train_freq, "batch_size": self.batch_size, "tau": self.tau, "ent_coef": self.ent_coef if isinstance(self.ent_coef, float) else 'auto', "target_entropy": self.target_entropy, # Should we also store the replay buffer? # this may lead to high memory usage # with all transition inside # "replay_buffer": self.replay_buffer "gamma": self.gamma, "verbose": self.verbose, "observation_space": self.observation_space, "action_space": self.action_space, "policy": self.policy, "n_envs": self.n_envs, "action_noise": self.action_noise, "random_exploration": self.random_exploration, "_vectorize_action": self._vectorize_action, "policy_kwargs": self.policy_kwargs } params_to_save = self.get_parameters() self._save_to_file(save_path, data=data, params=params_to_save, cloudpickle=cloudpickle)
[]
2024-01-10
whjvenyl/Neural-Photo-Editor
layers.py
### Custom Lasagne Layers for Introspective Adversarial Networks # A Brock, 2016 # # Layers that are not my own creation should be appropriately attributed here # MADE wrapped from the implementation by M. Germain et al: https://github.com/mgermain/MADE # Gaussian Sample layer from Tencia Lee's Recipe: https://github.com/Lasagne/Recipes/blob/master/examples/variational_autoencoder/variational_autoencoder.py # Minibatch Discrimination layer from OpenAI's Improved GAN Techniques: https://github.com/openai/improved-gan # Deconv Layer adapted from Radford's DCGAN: https://github.com/Newmu/dcgan_code from __future__ import division import numpy as np import theano import theano.tensor as T import lasagne import lasagne.layers from lasagne.layers import SliceLayer as SL from lasagne.layers import batch_norm as BN from lasagne.layers import ElemwiseSumLayer as ESL from lasagne.layers import NonlinearityLayer as NL from lasagne.layers import DenseLayer as DL from lasagne.init import Normal as initmethod from lasagne.nonlinearities import elu from lasagne.nonlinearities import rectify as relu from lasagne.nonlinearities import LeakyRectify as lrelu from lasagne.layers import TransposedConv2DLayer as TC2D from lasagne.layers import ConcatLayer as CL from math import sqrt from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from mask_generator import MaskGenerator # Multiscale Dilated Convolution Block # This function (not a layer in and of itself, though you could make it one) returns a set of concatenated conv2d and dilatedconv2d layers. # Each layer uses the same basic filter W, operating at a different dilation factor (or taken as the mean of W for the 1x1 conv). # The channel-wise output of each layer is weighted by a set of coefficients, which are initialized to 1 / the total number of dilation scales, # meaning that were starting by taking an elementwise mean. These should be learnable parameters. # NOTES: - I'm considering changing the variable names to be more descriptive, and look less like ridiculous academic code. It's on the to-do list. # - I keep the bias and nonlinearity out of the default definition for this layer, as I expect it to be batchnormed and nonlinearized in the model config. def MDCL(incoming,num_filters,scales,name,dnn=True): if dnn: from lasagne.layers.dnn import Conv2DDNNLayer as C2D # W initialization method--this should also work as Orthogonal('relu'), but I have yet to validate that as thoroughly. winit = initmethod(0.02) # Initialization method for the coefficients sinit = lasagne.init.Constant(1.0/(1+len(scales))) # Number of incoming channels ni =lasagne.layers.get_output_shape(incoming)[1] # Weight parameter--the primary parameter for this block W = theano.shared(lasagne.utils.floatX(winit.sample((num_filters,lasagne.layers.get_output_shape(incoming)[1],3,3))),name=name+'W') # Primary Convolution Layer--No Dilation n = C2D(incoming = incoming, num_filters = num_filters, filter_size = [3,3], stride = [1,1], pad = (1,1), W = W*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_base').dimshuffle(0,'x','x','x'), # Note the broadcasting dimshuffle for the num_filter scalars. b = None, nonlinearity = None, name = name+'base' ) # List of remaining layers. This should probably just all be concatenated into a single list rather than being a separate deal. nd = [] for i,scale in enumerate(scales): # I don't think 0 dilation is technically defined (or if it is it's just the regular filter) but I use it here as a convenient keyword to grab the 1x1 mean conv. if scale==0: nd.append(C2D(incoming = incoming, num_filters = num_filters, filter_size = [1,1], stride = [1,1], pad = (0,0), W = T.mean(W,axis=[2,3]).dimshuffle(0,1,'x','x')*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_1x1').dimshuffle(0,'x','x','x'), b = None, nonlinearity = None, name = name+str(scale))) # Note the dimshuffles in this layer--these are critical as the current DilatedConv2D implementation uses a backward pass. else: nd.append(lasagne.layers.DilatedConv2DLayer(incoming = lasagne.layers.PadLayer(incoming = incoming, width=(scale,scale)), num_filters = num_filters, filter_size = [3,3], dilation=(scale,scale), W = W.dimshuffle(1,0,2,3)*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_'+str(scale)).dimshuffle('x',0,'x','x'), b = None, nonlinearity = None, name = name+str(scale))) return ESL(nd+[n]) # MDC-based Upsample Layer. # This is a prototype I don't make use of extensively. It's operational but it doesn't seem to improve results yet. def USL(incoming,num_filters,scales,name,dnn=True): if dnn: from lasagne.layers.dnn import Conv2DDNNLayer as C2D # W initialization method--this should also work as Orthogonal('relu'), but I have yet to validate that as thoroughly. winit = initmethod(0.02) # Initialization method for the coefficients sinit = lasagne.init.Constant(1.0/(1+len(scales))) # Number of incoming channels ni =lasagne.layers.get_output_shape(incoming)[1] # Weight parameter--the primary parameter for this block W = theano.shared(lasagne.utils.floatX(winit.sample((num_filters,lasagne.layers.get_output_shape(incoming)[1],3,3))),name=name+'W') # Primary Convolution Layer--No Dilation n = C2D(incoming = Upscale2DLayer(incoming,2), num_filters = num_filters, filter_size = [3,3], stride = [1,1], pad = (1,1), W = W*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_base').dimshuffle(0,'x','x','x'), b = None, nonlinearity = None, name = name+'base' ) # Remaining layers nd = [] for i,scale in enumerate(scales): if scale==0: nd.append(C2D(incoming = Upscale2DLayer(incoming,2), num_filters = num_filters, filter_size = [1,1], stride = [1,1], pad = (0,0), W = T.mean(W,axis=[2,3]).dimshuffle(0,1,'x','x')*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_1x1').dimshuffle(0,'x','x','x'), b = None, nonlinearity = None, name = name+'1x1' )) else: nd.append(lasagne.layers.DilatedConv2DLayer(incoming = lasagne.layers.PadLayer(incoming = Upscale2DLayer(incoming,2), width=(scale,scale)), num_filters = num_filters, filter_size = [3,3], dilation=(scale,scale), W = W.dimshuffle(1,0,2,3)*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_'+str(scale)).dimshuffle('x',0,'x','x'), b = None, nonlinearity = None, name = name+str(scale))) # A single deconv layer is also concatenated here. Like I said, it's a prototype! nd.append(DeconvLayer(incoming = incoming, num_filters = num_filters, filter_size = [3,3], stride = [2,2], crop = (1,1), W = W.dimshuffle(1,0,2,3)*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_deconv').dimshuffle('x',0,'x','x'), b = None, nonlinearity = None, name = name+'deconv' )) return ESL(nd+[n]) #MDC-based Downsample Layer. # This is a prototype I don't make use of extensively. It's operational and it seems like it works alright, but it's restrictively expensive # and I am not PARALLELICUS, god of GPUs, so I don't have the memory to spare for it. # Note that this layer does not currently support having a 0 scale like the others do, and just has a 1x1-stride2 conv by default. def DSL(incoming,num_filters,scales,name,dnn=True): if dnn: from lasagne.layers.dnn import Conv2DDNNLayer as C2D # W initialization method--this should also work as Orthogonal('relu'), but I have yet to validate that as thoroughly. winit = initmethod(0.02) # Initialization method for the coefficients sinit = lasagne.init.Constant(1.0/(1+len(scales))) # Number of incoming channels ni =lasagne.layers.get_output_shape(incoming)[1] # Weight parameter--the primary parameter for this block W = theano.shared(lasagne.utils.floatX(winit.sample((num_filters,lasagne.layers.get_output_shape(incoming)[1],3,3))),name=name+'W') # Main layer--3x3 conv with stride 2 n = C2D(incoming = incoming, num_filters = num_filters, filter_size = [3,3], stride = [2,2], pad = (1,1), W = W*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_base').dimshuffle(0,'x','x','x'), b = None, nonlinearity = None, name = name+'base' ) nd = [] for i,scale in enumerate(scales): p = P2D(incoming = incoming, pool_size = scale, stride = 2, pad = (1,1) if i else (0,0), mode = 'average_exc_pad', ) nd.append(C2D(incoming = p, num_filters = num_filters, filter_size = [3,3], stride = (1,1), pad = (1,1), W = W*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_'+str(scale)).dimshuffle(0,'x','x','x'),#.dimshuffle('x',0), b = None, nonlinearity = None, name = name+str(scale))) nd.append(C2D(incoming = incoming, num_filters = num_filters, filter_size = [1,1], stride = [2,2], pad = (0,0), W = T.mean(W,axis=[2,3]).dimshuffle(0,1,'x','x')*theano.shared(lasagne.utils.floatX(sinit.sample(num_filters)), name+'_coeff_1x1').dimshuffle(0,'x','x','x'), b = None, nonlinearity = None, name = name+'1x1' )) return ESL(nd+[n]) # Beta Distribution Layer # This layer takes in a batch_size batch, 2-channel, NxN dimension layer and returns the output of the first channel # divided by the sum of both channels, which is equivalent to finding the expected value for a beta distribution. # Note that this version of the layer scales to {-1,1} for compatibility with tanh. class beta_layer(lasagne.layers.MergeLayer): def __init__(self, alpha,beta, **kwargs): super(beta_layer, self).__init__([alpha,beta], **kwargs) def get_output_shape_for(self, input_shape): print(input_shape) return input_shape[0] def get_output_for(self, inputs, deterministic=False, **kwargs): alpha,beta = inputs # return 2*T.true_div(alpha,T.add(alpha,beta)+1e-8)-1 return 2*(alpha/(alpha+beta+1e-8))-1 # Convenience Function to produce a residual pre-activation MDCL block def MDBLOCK(incoming,num_filters,scales,name,nonlinearity): return NL(BN(ESL([incoming, MDCL(NL(BN(MDCL(NL(BN(incoming,name=name+'bnorm0'),nonlinearity),num_filters,scales,name),name=name+'bnorm1'),nonlinearity), num_filters, scales, name+'2')]),name=name+'bnorm2'),nonlinearity) # Gaussian Sample Layer for VAE from Tencia Lee class GaussianSampleLayer(lasagne.layers.MergeLayer): def __init__(self, mu, logsigma, rng=None, **kwargs): self.rng = rng if rng else RandomStreams(lasagne.random.get_rng().randint(1,2147462579)) super(GaussianSampleLayer, self).__init__([mu, logsigma], **kwargs) def get_output_shape_for(self, input_shapes): return input_shapes[0] def get_output_for(self, inputs, deterministic=False, **kwargs): mu, logsigma = inputs shape=(self.input_shapes[0][0] or inputs[0].shape[0], self.input_shapes[0][1] or inputs[0].shape[1]) if deterministic: return mu return mu + T.exp(logsigma) * self.rng.normal(shape) # DeconvLayer adapted from Radford's DCGAN Implementation class DeconvLayer(lasagne.layers.conv.BaseConvLayer): def __init__(self, incoming, num_filters, filter_size, stride=(1, 1), crop=0, untie_biases=False, W=initmethod(), b=lasagne.init.Constant(0.), nonlinearity=lasagne.nonlinearities.rectify, flip_filters=False, **kwargs): super(DeconvLayer, self).__init__( incoming, num_filters, filter_size, stride, crop, untie_biases, W, b, nonlinearity, flip_filters, n=2, **kwargs) # rename self.crop to self.pad self.crop = self.pad del self.pad def get_W_shape(self): num_input_channels = self.input_shape[1] # first two sizes are swapped compared to a forward convolution return (num_input_channels, self.num_filters) + self.filter_size def get_output_shape_for(self, input_shape): # when called from the constructor, self.crop is still called self.pad: crop = getattr(self, 'crop', getattr(self, 'pad', None)) crop = crop if isinstance(crop, tuple) else (crop,) * self.n batchsize = input_shape[0] return(batchsize,self.num_filters)+(input_shape[2]*2,input_shape[3]*2) # return ((batchsize, self.num_filters) + # tuple(conv_input_length(input, filter, stride, p) # for input, filter, stride, p # in zip(input_shape[2:], self.filter_size, # self.stride, crop))) def convolve(self, input, **kwargs): # Messy to have these imports here, but seems to allow for switching DNN off. from theano.sandbox.cuda.basic_ops import (as_cuda_ndarray_variable, host_from_gpu, gpu_contiguous, HostFromGpu, gpu_alloc_empty) from theano.sandbox.cuda.dnn import GpuDnnConvDesc, GpuDnnConv, GpuDnnConvGradI, dnn_conv, dnn_pool # Straight outta Radford img = gpu_contiguous(input) kerns = gpu_contiguous(self.W) desc = GpuDnnConvDesc(border_mode=self.crop, subsample=self.stride, conv_mode='conv')(gpu_alloc_empty(img.shape[0], kerns.shape[1], img.shape[2]*self.stride[0], img.shape[3]*self.stride[1]).shape, kerns.shape) out = gpu_alloc_empty(img.shape[0], kerns.shape[1], img.shape[2]*self.stride[0], img.shape[3]*self.stride[1]) conved = GpuDnnConvGradI()(kerns, img, out, desc) return conved # Minibatch discrimination layer from OpenAI's improved GAN techniques class MinibatchLayer(lasagne.layers.Layer): def __init__(self, incoming, num_kernels, dim_per_kernel=5, theta=lasagne.init.Normal(0.05), log_weight_scale=lasagne.init.Constant(0.), b=lasagne.init.Constant(-1.), **kwargs): super(MinibatchLayer, self).__init__(incoming, **kwargs) self.num_kernels = num_kernels num_inputs = int(np.prod(self.input_shape[1:])) self.theta = self.add_param(theta, (num_inputs, num_kernels, dim_per_kernel), name="theta") self.log_weight_scale = self.add_param(log_weight_scale, (num_kernels, dim_per_kernel), name="log_weight_scale") self.W = self.theta * (T.exp(self.log_weight_scale)/T.sqrt(T.sum(T.square(self.theta),axis=0))).dimshuffle('x',0,1) self.b = self.add_param(b, (num_kernels,), name="b") def get_output_shape_for(self, input_shape): return (input_shape[0], np.prod(input_shape[1:])+self.num_kernels) def get_output_for(self, input, init=False, **kwargs): if input.ndim > 2: # if the input has more than two dimensions, flatten it into a # batch of feature vectors. input = input.flatten(2) activation = T.tensordot(input, self.W, [[1], [0]]) abs_dif = (T.sum(abs(activation.dimshuffle(0,1,2,'x') - activation.dimshuffle('x',1,2,0)),axis=2) + 1e6 * T.eye(input.shape[0]).dimshuffle(0,'x',1)) if init: mean_min_abs_dif = 0.5 * T.mean(T.min(abs_dif, axis=2),axis=0) abs_dif /= mean_min_abs_dif.dimshuffle('x',0,'x') self.init_updates = [(self.log_weight_scale, self.log_weight_scale-T.log(mean_min_abs_dif).dimshuffle(0,'x'))] f = T.sum(T.exp(-abs_dif),axis=2) if init: mf = T.mean(f,axis=0) f -= mf.dimshuffle('x',0) self.init_updates.append((self.b, -mf)) else: f += self.b.dimshuffle('x',0) return T.concatenate([input, f], axis=1) # Convenience function to define an inception-style block def InceptionLayer(incoming,param_dict,block_name): branch = [0]*len(param_dict) # Loop across branches for i,dict in enumerate(param_dict): for j,style in enumerate(dict['style']): # Loop up branch branch[i] = C2D( incoming = branch[i] if j else incoming, num_filters = dict['num_filters'][j], filter_size = dict['filter_size'][j], pad = dict['pad'][j] if 'pad' in dict else None, stride = dict['stride'][j], W = initmethod('relu'), nonlinearity = dict['nonlinearity'][j], name = block_name+'_'+str(i)+'_'+str(j)) if style=='convolutional'\ else NL(lasagne.layers.dnn.Pool2DDNNLayer( incoming=incoming if j == 0 else branch[i], pool_size = dict['filter_size'][j], mode = dict['mode'][j], stride = dict['stride'][j], pad = dict['pad'][j], name = block_name+'_'+str(i)+'_'+str(j)), nonlinearity = dict['nonlinearity'][j]) if style=='pool'\ else lasagne.layers.DilatedConv2DLayer( incoming = lasagne.layers.PadLayer(incoming = incoming if j==0 else branch[i],width = dict['pad'][j]) if 'pad' in dict else incoming if j==0 else branch[i], num_filters = dict['num_filters'][j], filter_size = dict['filter_size'][j], dilation = dict['dilation'][j], # pad = dict['pad'][j] if 'pad' in dict else None, W = initmethod('relu'), nonlinearity = dict['nonlinearity'][j], name = block_name+'_'+str(i)+'_'+str(j)) if style== 'dilation'\ else DL( incoming = incoming if j==0 else branch[i], num_units = dict['num_filters'][j], W = initmethod('relu'), b = None, nonlinearity = dict['nonlinearity'][j], name = block_name+'_'+str(i)+'_'+str(j)) # Apply Batchnorm branch[i] = BN(branch[i],name = block_name+'_bnorm_'+str(i)+'_'+str(j)) if dict['bnorm'][j] else branch[i] # Concatenate Sublayers return CL(incomings=branch,name=block_name) # Convenience function to define an inception-style block with upscaling def InceptionUpscaleLayer(incoming,param_dict,block_name): branch = [0]*len(param_dict) # Loop across branches for i,dict in enumerate(param_dict): for j,style in enumerate(dict['style']): # Loop up branch branch[i] = TC2D( incoming = branch[i] if j else incoming, num_filters = dict['num_filters'][j], filter_size = dict['filter_size'][j], crop = dict['pad'][j] if 'pad' in dict else None, stride = dict['stride'][j], W = initmethod('relu'), nonlinearity = dict['nonlinearity'][j], name = block_name+'_'+str(i)+'_'+str(j)) if style=='convolutional'\ else NL( incoming = lasagne.layers.dnn.Pool2DDNNLayer( incoming = lasagne.layers.Upscale2DLayer( incoming=incoming if j == 0 else branch[i], scale_factor = dict['stride'][j]), pool_size = dict['filter_size'][j], stride = [1,1], mode = dict['mode'][j], pad = dict['pad'][j], name = block_name+'_'+str(i)+'_'+str(j)), nonlinearity = dict['nonlinearity'][j]) # Apply Batchnorm branch[i] = BN(branch[i],name = block_name+'_bnorm_'+str(i)+'_'+str(j)) if dict['bnorm'][j] else branch[i] # Concatenate Sublayers return CL(incomings=branch,name=block_name) # Convenience function to efficiently generate param dictionaries for use with InceptioNlayer def pd(num_layers=2,num_filters=32,filter_size=(3,3),pad=1,stride = (1,1),nonlinearity=elu,style='convolutional',bnorm=1,**kwargs): input_args = locals() input_args.pop('num_layers') return {key:entry if type(entry) is list else [entry]*num_layers for key,entry in input_args.iteritems()} # Possible Conv2DDNN convenience function. Remember to delete the C2D import at the top if you use this # def C2D(incoming = None, num_filters = 32, filter_size= [3,3],pad = 'same',stride = [1,1], W = initmethod('relu'),nonlinearity = elu,name = None): # return lasagne.layers.dnn.Conv2DDNNLayer(incoming,num_filters,filter_size,stride,pad,False,W,None,nonlinearity,False) # Shape-Preserving Gaussian Sample layer for latent vectors with spatial dimensions. # This is a holdover from an "old" (i.e. I abandoned it last month) idea. class GSL(lasagne.layers.MergeLayer): def __init__(self, mu, logsigma, rng=None, **kwargs): self.rng = rng if rng else RandomStreams(lasagne.random.get_rng().randint(1,2147462579)) super(GSL, self).__init__([mu, logsigma], **kwargs) def get_output_shape_for(self, input_shape): print(input_shape) return input_shape[0] def get_output_for(self, inputs, deterministic=False, **kwargs): mu, logsigma = inputs if deterministic: return mu return mu + T.exp(logsigma) * self.rng.normal(logsigma.shape) # Convenience function to return list of sampled latent layers def GL(mu,ls): return([GSL(z_mu,z_ls) for z_mu,z_ls in zip(mu,ls)]) # Convenience function to return a residual layer. It's not really that much more convenient than ESL'ing, # but I like being able to see when I'm using Residual connections as opposed to Elemwise-sums def ResLayer(incoming, IB,nonlinearity): return NL(ESL([IB,incoming]),nonlinearity) # Inverse autoregressive flow layer class IAFLayer(lasagne.layers.MergeLayer): def __init__(self, z, mu, logsigma, **kwargs): super(IAFLayer, self).__init__([z,mu, logsigma], **kwargs) def get_output_shape_for(self, input_shapes): return input_shapes[0] def get_output_for(self, inputs, deterministic=False, **kwargs): z,mu, logsigma = inputs return (z - mu) / T.exp(logsigma) # Masked layer for MADE, adopted from M.Germain class MaskedLayer(lasagne.layers.DenseLayer): def __init__(self, incoming, num_units, mask_generator,layerIdx,W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.), nonlinearity=lasagne.nonlinearities.rectify, **kwargs): super(MaskedLayer, self).__init__(incoming, num_units, W,b, nonlinearity,**kwargs) self.mask_generator = mask_generator num_inputs = int(np.prod(self.input_shape[1:])) self.weights_mask = self.add_param(spec = np.ones((num_inputs, num_units),dtype=np.float32), shape = (num_inputs, num_units), name='weights_mask', trainable=False, regularizable=False) self.layerIdx = layerIdx self.shuffle_update = [(self.weights_mask, mask_generator.get_mask_layer_UPDATE(self.layerIdx))] def get_output_for(self,input, **kwargs): if input.ndim > 2: input = input.flatten(2) activation = T.dot(input, self.W*self.weights_mask) if self.b is not None: activation = activation + self.b.dimshuffle('x', 0) return self.nonlinearity(activation) # Stripped-Down Direct Input masked layer: Combine this with ESL and a masked layer to get a true DIML. # Consider making this a simultaneous subclass of MaskedLayer and elemwise sum layer for cleanliness # adopted from M.Germain class DIML(lasagne.layers.DenseLayer): def __init__(self, incoming, num_units, mask_generator,layerIdx,W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.), nonlinearity=None,**kwargs): super(DIML, self).__init__(incoming, num_units, W,b, nonlinearity,**kwargs) self.mask_generator = mask_generator self.layerIdx = layerIdx num_inputs = int(np.prod(self.input_shape[1:])) self.weights_mask = self.add_param(spec = np.ones((num_inputs, num_units),dtype=np.float32), shape = (num_inputs, num_units), name='weights_mask', trainable=False, regularizable=False) self.shuffle_update = [(self.weights_mask, self.mask_generator.get_direct_input_mask_layer_UPDATE(self.layerIdx + 1))] def get_output_for(self,input, **kwargs): if input.ndim > 2: input = input.flatten(2) activation = T.dot(input, self.W*self.weights_mask) if self.b is not None: activation = activation + self.b.dimshuffle('x', 0) return self.nonlinearity(activation) # Conditioning Masked Layer # Currently not used. # class CML(MaskedLayer): # def __init__(self, incoming, num_units, mask_generator,use_cond_mask=False,U=lasagne.init.GlorotUniform(),W=lasagne.init.GlorotUniform(), # b=init.Constant(0.), nonlinearity=lasagne.nonlinearities.rectify, **kwargs): # super(CML, self).__init__(incoming, num_units, mask_generator,W, # b, nonlinearity,**kwargs) # self.use_cond_mask=use_cond_mask # if use_cond_mask: # self.U = self.add_param(spec = U, # shape = (num_inputs, num_units), # name='U', # trainable=True, # regularizable=False)theano.shared(value=self.weights_initialization((self.n_in, self.n_out)), name=self.name+'U', borrow=True) # self.add_param(self.U,name = # def get_output_for(self,input,**kwargs): # lin = self.lin_output = T.dot(input, self.W * self.weights_mask) + self.b # if self.use_cond_mask: # lin = lin+T.dot(T.ones_like(input), self.U * self.weights_mask) # return lin if self._activation is None else self._activation(lin) # Made layer, adopted from M.Germain class MADE(lasagne.layers.Layer): def __init__(self,z,hidden_sizes,name,nonlinearity=lasagne.nonlinearities.rectify,output_nonlinearity=None, **kwargs): # self.rng = rng if rng else RandomStreams(lasagne.random.get_rng().randint(1234)) super(MADE, self).__init__(z, **kwargs) # Incoming latents self.z = z # List defining hidden units in each layer self.hidden_sizes = hidden_sizes # Layer name for saving parameters. self.name = name # nonlinearity self.nonlinearity = nonlinearity # Output nonlinearity self.output_nonlinearity = output_nonlinearity # Control parameters from original MADE mask_distribution=0 use_cond_mask = False direct_input_connect = "Output" direct_output_connect = False self.shuffled_once = False # Mask generator self.mask_generator = MaskGenerator(lasagne.layers.get_output_shape(z)[1], hidden_sizes, mask_distribution) # Build the MADE # TODO: Consider making this more compact by directly writing to the layers list self.input_layer = MaskedLayer(incoming = z, num_units = hidden_sizes[0], mask_generator = self.mask_generator, layerIdx = 0, W = lasagne.init.Orthogonal('relu'), nonlinearity=self.nonlinearity, name = self.name+'_input') self.layers = [self.input_layer] for i in range(1, len(hidden_sizes)): self.layers += [MaskedLayer(incoming = self.layers[-1], num_units = hidden_sizes[i], mask_generator = self.mask_generator, layerIdx = i, W = lasagne.init.Orthogonal('relu'), nonlinearity=self.nonlinearity, name = self.name+'_layer_'+str(i))] outputLayerIdx = len(self.layers) # Output layer self.layers += [MaskedLayer(incoming = self.layers[-1], num_units = lasagne.layers.get_output_shape(z)[1], mask_generator = self.mask_generator, layerIdx = outputLayerIdx, W = lasagne.init.Orthogonal('relu'), nonlinearity = self.output_nonlinearity, name = self.name+'_output_W'), DIML(incoming = z, num_units = lasagne.layers.get_output_shape(z)[1], mask_generator = self.mask_generator, layerIdx = outputLayerIdx, W = lasagne.init.Orthogonal('relu'), nonlinearity = self.output_nonlinearity, name = self.name+'_output_D')] masks_updates = [layer_mask_update for l in self.layers for layer_mask_update in l.shuffle_update] self.update_masks = theano.function(name='update_masks', inputs=[], updates=masks_updates) # Make the true output layer by ESL'ing the DIML and masked layer self.final_layer= ESL([self.layers[-2],self.layers[-1]]) # self.output_layer = self.layers[-1] # params = [p for p in l.get_params(trainable=True) for l in self.layers] # print(params) def get_output_for(self, input, deterministic=False, **kwargs): return lasagne.layers.get_output(self.final_layer,{self.z:input}) def get_params(self, unwrap_shared=True, **tags): params = [] for l in self.layers: for p in l.get_params(**tags): params.append(p) return(params) # params = [p for p in l.get_params(trainable=True) for l in self.layers] # return params # return [p for p in lay.get_params(unwrap_shared,**tags) for lay in self.layers] # return lasagne.layers.get_all_params(self.final_layer,trainable=True) def shuffle(self, shuffling_type): if shuffling_type == "Once" and self.shuffled_once is False: self.mask_generator.shuffle_ordering() self.mask_generator.sample_connectivity() self.update_masks() self.shuffled_once = True return if shuffling_type in ["Ordering", "Full"]: self.mask_generator.shuffle_ordering() if shuffling_type in ["Connectivity", "Full"]: self.mask_generator.sample_connectivity() self.update_masks() def reset(self, shuffling_type, last_shuffle=0): self.mask_generator.reset() # Always do a first shuffle so that the natural order does not gives us an edge self.shuffle("Full") # Set the mask to the requested shuffle for i in range(last_shuffle): self.shuffle(shuffling_type)
[]
2024-01-10
JosephTLucas/llm_test
oai_template.py
import json import requests import os import openai class Model: def __init__( self, model="text-davinci-002", temperature=0, max_tokens=128, stop=None ): self.model = model openai.api_key = os.getenv("oai_key") self.temperature = temperature self.max_tokens = max_tokens self.stop = stop def query(self, query): response = openai.Completion.create( prompt=query, model=self.model, temperature=self.temperature, max_tokens=self.max_tokens, stop=self.stop, ) return response.choices[0].text.strip() if __name__ == "__main__": m = Model("text-davinci-002") print(m.query("I like apples because"))
[]
2024-01-10
wensle/dotsavvy
dotsavvy~services~chunk.py
from typing import AbstractSet, Collection, Literal from langchain.text_splitter import RecursiveCharacterTextSplitter from dotsavvy.utils.env_variables import get_env_variable # Constants _CHUNK_SIZE = 400 _CHUNK_OVERLAP = 20 _ALLOWED_SPECIAL = "all" _DISALLOWED_SPECIAL = "all" def get_text_chunks( text: str, chunk_size: int | None = None, chunk_overlap: int | None = None, model_name: str | None = None, encoding_name: str | None = None, ) -> list[str]: """ Splits the provided text into smaller chunks using the RecursiveCharacterTextSplitter. The RecursiveCharacterTextSplitter divides text into chunks based on a list of characters, prioritizing splitting at paragraph breaks, then at line breaks, spaces, and if necessary, any character. This maintains continuity and semantic relationship as much as possible. """ # Use the provided values or the default ones chunk_size = chunk_size or _CHUNK_SIZE chunk_overlap = chunk_overlap or _CHUNK_OVERLAP model_name = model_name or get_env_variable("DOTSAVVY_LLM_NAME") encoding_name = encoding_name or get_env_variable( "DOTSAVVY_TOKENIZER_ENCODING_NAME" ) text_splitter: RecursiveCharacterTextSplitter = ( RecursiveCharacterTextSplitter.from_tiktoken_encoder( chunk_size=chunk_size, chunk_overlap=chunk_overlap, encoding_name=encoding_name, model_name=model_name, ) ) chunks: list[str] = text_splitter.split_text(text) return chunks def create_recursive_tiktoken_splitter( chunk_size: int | None = None, chunk_overlap: int | None = None, encoding_name: str | None = None, model_name: str | None = None, allowed_special: AbstractSet[str] | Literal["all"] | None = None, disallowed_special: Collection[str] | Literal["all"] | None = None, ) -> RecursiveCharacterTextSplitter: """ Returns a LangChain RecursiveCharacterTextSplitter object. The RecursiveCharacterTextSplitter divides text into chunks based on a list of characters, prioritizing splitting at paragraph breaks, then at line breaks, spaces, and if necessary, any character. This maintains continuity and semantic relationship as much as possible. """ # Use the provided values or the default ones chunk_size = chunk_size or _CHUNK_SIZE chunk_overlap = chunk_overlap or _CHUNK_OVERLAP encoding_name = encoding_name or get_env_variable( "DOTSAVVY_TOKENIZER_ENCODING_NAME" ) model_name = model_name or get_env_variable("DOTSAVVY_LLM_NAME") allowed_special = allowed_special or _ALLOWED_SPECIAL disallowed_special = disallowed_special or _DISALLOWED_SPECIAL text_splitter: RecursiveCharacterTextSplitter = ( RecursiveCharacterTextSplitter.from_tiktoken_encoder( chunk_size=chunk_size, chunk_overlap=chunk_overlap, encoding_name=encoding_name, model_name=model_name, allowed_special=allowed_special, disallowed_special=disallowed_special, ) ) return text_splitter
[]
2024-01-10
wensle/dotsavvy
dotsavvy~agents~conversation.py
from langchain.chains import RetrievalQA from langchain.chains.conversation.memory import ConversationBufferWindowMemory from langchain.chat_models import ChatOpenAI from dotsavvy.services.vectorstore import create_pinecone_vectorstore from dotsavvy.utils.env_variables import get_env_variable class ConversationAgent: def __init__(self) -> None: openai_api_key: str = get_env_variable("OPENAI_API_KEY") llm_name: str = get_env_variable("DOTSAVVY_LLM_NAME") self.chat_model = ChatOpenAI(openai_api_key=openai_api_key, model_name=llm_name) self.memory = ConversationBufferWindowMemory( memory_key="chat_history", k=5, return_messages=True ) vectorstore = create_pinecone_vectorstore() self.retrieval_qa = RetrievalQA.from_chain_type( llm=self.chat_model, chain_type="stuff", retriever=vectorstore.as_retriever(), ) def run(self, query: str) -> str: return self.retrieval_qa.run(query=query)
[]
2024-01-10
wensle/dotsavvy
data~pdfs~scripts~split_embed_raw_data.py
import json import pickle from pathlib import Path from typing import Generator from uuid import uuid4 from langchain.document_loaders import PyPDFLoader from config import ICT_RESEARCH_METHODS_BASE_DIR, PDFS_BASE_DIR from dotsavvy.datastore.pinecone.types import METADATA from dotsavvy.services.chunk import create_recursive_tiktoken_splitter from dotsavvy.services.embedding import embed_documents _INPUT_DIR: Path = PDFS_BASE_DIR / "raw_data" _OUTPUT_FILE_PATH: Path = PDFS_BASE_DIR / "processed_data" / "embedding_tuples.pkl" def ingest_file(filepath: str | Path) -> tuple[list[str], list[METADATA]]: """A helper function to load the input file containing processed data.""" with open(filepath, "r") as f: json_obj = json.load(f) return json_obj["texts"], json_obj["metadatas"] def process_dir_generator( input_dir: Path, ) -> Generator[tuple[str, METADATA], None, None]: for raw_data_file in input_dir.glob("*.pdf"): yield str(raw_data_file) def main( input_dir: Path | None = None, output_file_path: str | Path | None = None, ) -> None: input_dir = input_dir or _INPUT_DIR output_file_path = output_file_path or _OUTPUT_FILE_PATH text_splitter = create_recursive_tiktoken_splitter() chunks = [] metadatas = [] uuids = [] for raw_data_file in process_dir_generator(input_dir): loader = PyPDFLoader(raw_data_file) print(raw_data_file) for document in loader.lazy_load(): for chunk_id, chunk in enumerate( text_splitter.split_text(document.page_content) ): chunks.append(chunk) document.metadata["chunk_id"] = chunk_id document.metadata["text"] = chunk metadatas.append(document.metadata) uuids.append(str(uuid4())) embeddings = embed_documents(chunks) embedding_tuples = list(zip(uuids, embeddings, metadatas)) with open(_OUTPUT_FILE_PATH, "wb") as pkl: pickle.dump(embedding_tuples, pkl) if __name__ == "__main__": main()
[]
2024-01-10
khanhnn00/kernel-prior-diffusion
improved_diffusion~logger.py
""" Logger copied from OpenAI baselines to avoid extra RL-based dependencies: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py """ import os import sys import shutil import os.path as osp import json import time import datetime import tempfile import warnings from collections import defaultdict from contextlib import contextmanager DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, "wt") self.own_file = True else: assert hasattr(filename_or_file, "read"), ( "expected file or str, got %s" % filename_or_file ) self.file = filename_or_file self.own_file = False def writekvs(self, kvs): # Create strings for printing key2str = {} for (key, val) in sorted(kvs.items()): if hasattr(val, "__float__"): valstr = "%-8.3g" % val else: valstr = str(val) key2str[self._truncate(key)] = self._truncate(valstr) # Find max widths if len(key2str) == 0: print("WARNING: tried to write empty key-value dict") return else: keywidth = max(map(len, key2str.keys())) valwidth = max(map(len, key2str.values())) # Write out the data dashes = "-" * (keywidth + valwidth + 7) lines = [dashes] for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()): lines.append( "| %s%s | %s%s |" % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val))) ) lines.append(dashes) self.file.write("\n".join(lines) + "\n") # Flush the output to the file self.file.flush() def _truncate(self, s): maxlen = 30 return s[: maxlen - 3] + "..." if len(s) > maxlen else s def writeseq(self, seq): seq = list(seq) for (i, elem) in enumerate(seq): self.file.write(elem) if i < len(seq) - 1: # add space unless this is the last one self.file.write(" ") self.file.write("\n") self.file.flush() def close(self): if self.own_file: self.file.close() class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, "wt") def writekvs(self, kvs): for k, v in sorted(kvs.items()): if hasattr(v, "dtype"): kvs[k] = float(v) self.file.write(json.dumps(kvs) + "\n") self.file.flush() def close(self): self.file.close() class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, "w+t") self.keys = [] self.sep = "," def writekvs(self, kvs): # Add our current row to the history extra_keys = list(kvs.keys() - self.keys) extra_keys.sort() if extra_keys: self.keys.extend(extra_keys) self.file.seek(0) lines = self.file.readlines() self.file.seek(0) for (i, k) in enumerate(self.keys): if i > 0: self.file.write(",") self.file.write(k) self.file.write("\n") for line in lines[1:]: self.file.write(line[:-1]) self.file.write(self.sep * len(extra_keys)) self.file.write("\n") for (i, k) in enumerate(self.keys): if i > 0: self.file.write(",") v = kvs.get(k) if v is not None: self.file.write(str(v)) self.file.write("\n") self.file.flush() def close(self): self.file.close() class TensorBoardOutputFormat(KVWriter): """ Dumps key/value pairs into TensorBoard's numeric format. """ def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = "events" path = osp.join(osp.abspath(dir), prefix) import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.core.util import event_pb2 from tensorflow.python.util import compat self.tf = tf self.event_pb2 = event_pb2 self.pywrap_tensorflow = pywrap_tensorflow self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) def writekvs(self, kvs): def summary_val(k, v): kwargs = {"tag": k, "simple_value": float(v)} return self.tf.Summary.Value(**kwargs) summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) event = self.event_pb2.Event(wall_time=time.time(), summary=summary) event.step = ( self.step ) # is there any reason why you'd want to specify the step? self.writer.WriteEvent(event) self.writer.Flush() self.step += 1 def close(self): if self.writer: self.writer.Close() self.writer = None def make_output_format(format, ev_dir, log_suffix=""): os.makedirs(ev_dir, exist_ok=True) if format == "stdout": return HumanOutputFormat(sys.stdout) elif format == "log": return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix)) elif format == "json": return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix)) elif format == "csv": return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix)) elif format == "tensorboard": return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix)) else: raise ValueError("Unknown format specified: %s" % (format,)) # ================================================================ # API # ================================================================ def logkv(key, val): """ Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration If called many times, last value will be used. """ get_current().logkv(key, val) def logkv_mean(key, val): """ The same as logkv(), but if called many times, values averaged. """ get_current().logkv_mean(key, val) def logkvs(d): """ Log a dictionary of key-value pairs """ for (k, v) in d.items(): logkv(k, v) def dumpkvs(): """ Write all of the diagnostics from the current iteration """ return get_current().dumpkvs() def getkvs(): return get_current().name2val def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ get_current().log(*args, level=level) def debug(*args): log(*args, level=DEBUG) def info(*args): log(*args, level=INFO) def warn(*args): log(*args, level=WARN) def error(*args): log(*args, level=ERROR) def set_level(level): """ Set logging threshold on current logger. """ get_current().set_level(level) def set_comm(comm): get_current().set_comm(comm) def get_dir(): """ Get directory that log files are being written to. will be None if there is no output directory (i.e., if you didn't call start) """ return get_current().get_dir() record_tabular = logkv dump_tabular = dumpkvs @contextmanager def profile_kv(scopename): logkey = "wait_" + scopename tstart = time.time() try: yield finally: get_current().name2val[logkey] += time.time() - tstart def profile(n): """ Usage: @profile("my_func") def my_func(): code """ def decorator_with_name(func): def func_wrapper(*args, **kwargs): with profile_kv(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name # ================================================================ # Backend # ================================================================ def get_current(): if Logger.CURRENT is None: _configure_default_logger() return Logger.CURRENT class Logger(object): DEFAULT = None # A logger with no output files. (See right below class definition) # So that you can still log to the terminal without setting up any output files CURRENT = None # Current logger being used by the free functions above def __init__(self, dir, output_formats, comm=None): self.name2val = defaultdict(float) # values this iteration self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats self.comm = comm # Logging API, forwarded # ---------------------------------------- def logkv(self, key, val): self.name2val[key] = val def logkv_mean(self, key, val): oldval, cnt = self.name2val[key], self.name2cnt[key] self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1) self.name2cnt[key] = cnt + 1 def dumpkvs(self): if self.comm is None: d = self.name2val else: d = mpi_weighted_mean( self.comm, { name: (val, self.name2cnt.get(name, 1)) for (name, val) in self.name2val.items() }, ) if self.comm.rank != 0: d["dummy"] = 1 # so we don't get a warning about empty dict out = d.copy() # Return the dict for unit testing purposes for fmt in self.output_formats: if isinstance(fmt, KVWriter): fmt.writekvs(d) self.name2val.clear() self.name2cnt.clear() return out def log(self, *args, level=INFO): if self.level <= level: self._do_log(args) # Configuration # ---------------------------------------- def set_level(self, level): self.level = level def set_comm(self, comm): self.comm = comm def get_dir(self): return self.dir def close(self): for fmt in self.output_formats: fmt.close() # Misc # ---------------------------------------- def _do_log(self, args): for fmt in self.output_formats: if isinstance(fmt, SeqWriter): fmt.writeseq(map(str, args)) def get_rank_without_mpi_import(): # check environment variables here instead of importing mpi4py # to avoid calling MPI_Init() when this module is imported for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]: if varname in os.environ: return int(os.environ[varname]) return 0 def mpi_weighted_mean(comm, local_name2valcount): """ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110 Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key -> (value, count) Returns: key -> mean """ all_name2valcount = comm.gather(local_name2valcount) if comm.rank == 0: name2sum = defaultdict(float) name2count = defaultdict(float) for n2vc in all_name2valcount: for (name, (val, count)) in n2vc.items(): try: val = float(val) except ValueError: if comm.rank == 0: warnings.warn( "WARNING: tried to compute mean on non-float {}={}".format( name, val ) ) else: name2sum[name] += val * count name2count[name] += count return {name: name2sum[name] / name2count[name] for name in name2sum} else: return {} def configure(dir=None, format_strs=None, comm=None, log_suffix=""): """ If comm is provided, average all numerical stats across that comm """ if dir is None: dir = os.getenv("OPENAI_LOGDIR") if dir is None: dir = osp.join( tempfile.gettempdir(), datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"), ) assert isinstance(dir, str) dir = os.path.expanduser(dir) os.makedirs(os.path.expanduser(dir), exist_ok=True) rank = get_rank_without_mpi_import() if rank > 0: log_suffix = log_suffix + "-rank%03i" % rank if format_strs is None: if rank == 0: format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",") else: format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",") format_strs = filter(None, format_strs) output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm) if output_formats: log("Logging to %s" % dir) def _configure_default_logger(): configure() Logger.DEFAULT = Logger.CURRENT def reset(): if Logger.CURRENT is not Logger.DEFAULT: Logger.CURRENT.close() Logger.CURRENT = Logger.DEFAULT log("Reset logger") @contextmanager def scoped_configure(dir=None, format_strs=None, comm=None): prevlogger = Logger.CURRENT configure(dir=dir, format_strs=format_strs, comm=comm) try: yield finally: Logger.CURRENT.close() Logger.CURRENT = prevlogger
[]
2024-01-10
roy0428/ADL_Final
GPT_on_test.py
from openai import OpenAI from tqdm import tqdm import json def main(): with open("data/test_zero.json") as file: data_list = json.load(file) api_key = "APIKEY" client = OpenAI(api_key=api_key) for data in tqdm(data_list["data"]): system_content = data["instruction"][:53] user_content = data["instruction"][53:] response = client.chat.completions.create( model="gpt-4-vision-preview", # model = "gpt-3.5-turbo-1106", messages=[ {"role": "system", "content": system_content}, {"role": "user", "content": user_content}, ], max_tokens=200, ) output = response.choices[0].message.content data["prediction"] = output[3:] json.dump(data_list["data"], open("GPT4_0.json", "w"), indent=2, ensure_ascii=False) if __name__ == "__main__": main()
[]
2024-01-10
the-genemachine/Color-Prompt-Generator
color-generator-tkinter.py
import os import tkinter as tk import ast import openai from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") def display_colors(colors): root = tk.Tk() for color in colors: frame = tk.Frame(root, bg=color, height=150, width=200) frame.pack(fill='both') root.mainloop() def generate_palette(prompt_text): prompt = f""" You are a color palette generating assistant that responds to text prompts for color palettes. Based on the following prompt: '{prompt_text}', please generate a palette of 5 colors in the format: ["#color1", "#color2", "#color3", "#color4", "#color5"] """ response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=100, temperature=0.3 ) # Error checking for AI response try: colors = ast.literal_eval(response.choices[0].text.strip()) if isinstance(colors, list) and all(isinstance(item, str) for item in colors): display_colors(colors) else: print(f"Unexpected response: {response.choices[0].text.strip()}") except (ValueError, SyntaxError): print(f"Couldn't parse response: {response.choices[0].text.strip()}") generate_palette("A beautiful sunset")
[ "\n You are a color palette generating assistant that responds to text prompts for color palettes.\n Based on the following prompt: 'PLACEHOLDER', please generate a palette of 5 colors in the format: [\"#color1\", \"#color2\", \"#color3\", \"#color4\", \"#color5\"]\n " ]
2024-01-10
the-genemachine/Color-Prompt-Generator
color-generator.py
import openai import json import tkinter from dotenv import dotenv_values config = dotenv_values(".env") openai.api_key = config["OPENAI_API_KEY"] # This is a multiline string that describes the task to be completed by the OpenAI model. prompt = """ You are a color palette generating assitant that responds to text prompts for color palettes You should generate color palettes that are aesthetically pleasing and match the text prompt You should generate 5 colors per palette Desired Format: a JSON array of hex color codes Text : A beautiful sunset Result : ["#FFC300", "#FF5733", "#C70039", "#900C3F", "#581845"] """ # This line sends the prompt to the OpenAI API and stores the response response = openai.Completion.create( model="text-davinci-003", prompt=prompt, max_tokens=200 ) # This line prints out the actual generated text which is stored under the choices key in the response print(response["choices"][0] ["text"])
[ "\nYou are a color palette generating assitant that responds to text prompts for color palettes\n\nYou should generate color palettes that are aesthetically pleasing and match the text prompt\n\nYou should generate 5 colors per palette\n\nDesired Format: a JSON array of hex color codes\n\nText : A beautiful sunset\n\nResult : [\"#FFC300\", \"#FF5733\", \"#C70039\", \"#900C3F\", \"#581845\"]\n" ]
2024-01-10
dki-lab/GrailQA
allennlp~tests~data~tokenizers~word_splitter_test.py
# pylint: disable=no-self-use,invalid-name import spacy from allennlp.common.testing import AllenNlpTestCase from allennlp.data.tokenizers.token import Token from allennlp.data.tokenizers.word_splitter import LettersDigitsWordSplitter from allennlp.data.tokenizers.word_splitter import SimpleWordSplitter from allennlp.data.tokenizers.word_splitter import SpacyWordSplitter from allennlp.data.tokenizers.word_splitter import OpenAISplitter from allennlp.data.tokenizers.word_splitter import BertBasicWordSplitter class TestSimpleWordSplitter(AllenNlpTestCase): def setUp(self): super(TestSimpleWordSplitter, self).setUp() self.word_splitter = SimpleWordSplitter() def test_tokenize_handles_complex_punctuation(self): sentence = "this (sentence) has 'crazy' \"punctuation\"." expected_tokens = ["this", "(", "sentence", ")", "has", "'", "crazy", "'", '"', "punctuation", '"', "."] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_contraction(self): sentence = "it ain't joe's problem; would've been yesterday" expected_tokens = ["it", "ai", "n't", "joe", "'s", "problem", ";", "would", "'ve", "been", "yesterday"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_batch_tokenization(self): sentences = ["This is a sentence", "This isn't a sentence.", "This is the 3rd sentence." "Here's the 'fourth' sentence."] batch_split = self.word_splitter.batch_split_words(sentences) separately_split = [self.word_splitter.split_words(sentence) for sentence in sentences] assert len(batch_split) == len(separately_split) for batch_sentence, separate_sentence in zip(batch_split, separately_split): assert len(batch_sentence) == len(separate_sentence) for batch_word, separate_word in zip(batch_sentence, separate_sentence): assert batch_word.text == separate_word.text def test_tokenize_handles_multiple_contraction(self): sentence = "wouldn't've" expected_tokens = ["would", "n't", "'ve"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_final_apostrophe(self): sentence = "the jones' house" expected_tokens = ["the", "jones", "'", "house"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_special_cases(self): sentence = "mr. and mrs. jones, etc., went to, e.g., the store" expected_tokens = ["mr.", "and", "mrs.", "jones", ",", "etc.", ",", "went", "to", ",", "e.g.", ",", "the", "store"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens class TestLettersDigitsWordSplitter(AllenNlpTestCase): def setUp(self): super(TestLettersDigitsWordSplitter, self).setUp() self.word_splitter = LettersDigitsWordSplitter() def test_tokenize_handles_complex_punctuation(self): sentence = "this (sentence) has 'crazy' \"punctuation\"." expected_tokens = ["this", "(", "sentence", ")", "has", "'", "crazy", "'", '"', "punctuation", '"', "."] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_unicode_letters(self): sentence = "HAL9000 and Ångström" expected_tokens = [Token("HAL", 0), Token("9000", 3), Token("and", 10), Token("Ångström", 17)] tokens = self.word_splitter.split_words(sentence) assert [t.text for t in tokens] == [t.text for t in expected_tokens] assert [t.idx for t in tokens] == [t.idx for t in expected_tokens] def test_tokenize_handles_splits_all_punctuation(self): sentence = "wouldn't.[have] -3.45(m^2)" expected_tokens = ["wouldn", "'", "t", ".", "[", "have", "]", "-", "3", ".", "45", "(", "m", "^", "2", ")"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens class TestSpacyWordSplitter(AllenNlpTestCase): def setUp(self): super(TestSpacyWordSplitter, self).setUp() self.word_splitter = SpacyWordSplitter() def test_tokenize_handles_complex_punctuation(self): sentence = "this (sentence) has 'crazy' \"punctuation\"." expected_tokens = ["this", "(", "sentence", ")", "has", "'", "crazy", "'", '"', "punctuation", '"', "."] tokens = self.word_splitter.split_words(sentence) token_text = [t.text for t in tokens] assert token_text == expected_tokens for token in tokens: start = token.idx end = start + len(token.text) assert sentence[start:end] == token.text def test_tokenize_handles_contraction(self): # note that "would've" is kept together, while "ain't" is not. sentence = "it ain't joe's problem; would been yesterday" expected_tokens = ["it", "ai", "n't", "joe", "'s", "problem", ";", "would", "been", "yesterday"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_multiple_contraction(self): sentence = "wouldn't've" expected_tokens = ["would", "n't", "'ve"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_final_apostrophe(self): sentence = "the jones' house" expected_tokens = ["the", "jones", "'", "house"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_removes_whitespace_tokens(self): sentence = "the\n jones' house \x0b 55" expected_tokens = ["the", "jones", "'", "house", "55"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_tokenize_handles_special_cases(self): # note that the etc. doesn't quite work --- we can special case this if we want. sentence = "Mr. and Mrs. Jones, etc., went to, e.g., the store" expected_tokens = ["Mr.", "and", "Mrs.", "Jones", ",", "etc", ".", ",", "went", "to", ",", "e.g.", ",", "the", "store"] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_batch_tokenization(self): sentences = ["This is a sentence", "This isn't a sentence.", "This is the 3rd sentence." "Here's the 'fourth' sentence."] batch_split = self.word_splitter.batch_split_words(sentences) separately_split = [self.word_splitter.split_words(sentence) for sentence in sentences] assert len(batch_split) == len(separately_split) for batch_sentence, separate_sentence in zip(batch_split, separately_split): assert len(batch_sentence) == len(separate_sentence) for batch_word, separate_word in zip(batch_sentence, separate_sentence): assert batch_word.text == separate_word.text def test_keep_spacy_tokens(self): word_splitter = SpacyWordSplitter() sentence = "This should be an allennlp Token" tokens = word_splitter.split_words(sentence) assert tokens assert all(isinstance(token, Token) for token in tokens) word_splitter = SpacyWordSplitter(keep_spacy_tokens=True) sentence = "This should be a spacy Token" tokens = word_splitter.split_words(sentence) assert tokens assert all(isinstance(token, spacy.tokens.Token) for token in tokens) class TestOpenAiWordSplitter(AllenNlpTestCase): def setUp(self): super(TestOpenAiWordSplitter, self).setUp() self.word_splitter = OpenAISplitter() def test_tokenize_handles_complex_punctuation(self): sentence = "This sentence ?a!?!" expected_tokens = ['This', 'sentence', '?', 'a', '!', '?', '!'] tokens = [t.text for t in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens class TestBertBasicWordSplitter(AllenNlpTestCase): def setUp(self): super(TestBertBasicWordSplitter, self).setUp() self.word_splitter = BertBasicWordSplitter() def test_never_split(self): sentence = "[unused0] [UNK] [SEP] [PAD] [CLS] [MASK]" expected_tokens = ["[", "unused0", "]", "[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]"] tokens = [token.text for token in self.word_splitter.split_words(sentence)] assert tokens == expected_tokens def test_do_lower_case(self): # BertBasicWordSplitter makes every token not in `never_split` to lowercase by default word_splitter = BertBasicWordSplitter(never_split=["[UNUSED0]"]) sentence = "[UNUSED0] [UNK] [unused0]" expected_tokens = ["[UNUSED0]", "[", "unk", "]", "[", "unused0", "]"] tokens = [token.text for token in word_splitter.split_words(sentence)] assert tokens == expected_tokens
[]
2024-01-10
lega0208/lancedb
docs~src~examples~modal_langchain.py
import pickle import re import sys import zipfile from pathlib import Path import requests from langchain.chains import RetrievalQA from langchain.document_loaders import UnstructuredHTMLLoader from langchain.embeddings import OpenAIEmbeddings from langchain.llms import OpenAI from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import LanceDB from modal import Image, Secret, Stub, web_endpoint import lancedb lancedb_image = Image.debian_slim().pip_install( "lancedb", "langchain", "openai", "pandas", "tiktoken", "unstructured", "tabulate" ) stub = Stub( name="example-langchain-lancedb", image=lancedb_image, secrets=[Secret.from_name("my-openai-secret")], ) docsearch = None docs_path = Path("docs.pkl") db_path = Path("lancedb") def get_document_title(document): m = str(document.metadata["source"]) title = re.findall("pandas.documentation(.*).html", m) if title[0] is not None: return title[0] return "" def download_docs(): pandas_docs = requests.get( "https://eto-public.s3.us-west-2.amazonaws.com/datasets/pandas_docs/pandas.documentation.zip" ) with open(Path("pandas.documentation.zip"), "wb") as f: f.write(pandas_docs.content) file = zipfile.ZipFile(Path("pandas.documentation.zip")) file.extractall(path=Path("pandas_docs")) def store_docs(): docs = [] if not docs_path.exists(): for p in Path("pandas_docs/pandas.documentation").rglob("*.html"): if p.is_dir(): continue loader = UnstructuredHTMLLoader(p) raw_document = loader.load() m = {} m["title"] = get_document_title(raw_document[0]) m["version"] = "2.0rc0" raw_document[0].metadata = raw_document[0].metadata | m raw_document[0].metadata["source"] = str(raw_document[0].metadata["source"]) docs = docs + raw_document with docs_path.open("wb") as fh: pickle.dump(docs, fh) else: with docs_path.open("rb") as fh: docs = pickle.load(fh) return docs def qanda_langchain(query): download_docs() docs = store_docs() text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200,) documents = text_splitter.split_documents(docs) embeddings = OpenAIEmbeddings() db = lancedb.connect(db_path) table = db.create_table( "pandas_docs", data=[ { "vector": embeddings.embed_query("Hello World"), "text": "Hello World", "id": "1", } ], mode="overwrite", ) docsearch = LanceDB.from_documents(documents, embeddings, connection=table) qa = RetrievalQA.from_chain_type( llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever() ) return qa.run(query) @stub.function() @web_endpoint(method="GET") def web(query: str): answer = qanda_langchain(query) return { "answer": answer, } @stub.function() def cli(query: str): answer = qanda_langchain(query) print(answer)
[]
2024-01-10
gutbash/gpt-iva-cord
test_chat_agent.py
import discord from discord import app_commands import discord.ext.commands import discord.ext.tasks from utils.log_utils import colors from utils.redis_utils import save_pickle_to_redis, load_pickle_from_redis from utils.postgres_utils import fetch_key, fetch_keys_table, upsert_key, delete_key from utils.tool_utils import dummy_sync_function from tools import ( get_image_from_search, get_organic_results, get_shopping_results, question_answer_webpage, summarize_webpage, get_full_blip, ) import asyncio import os import openai import datetime from transformers import GPT2TokenizerFast import re import requests import itertools import pydot import PyPDF2 import io import textwrap from bs4 import BeautifulSoup import chardet import aiohttp import logging from langchain.chat_models import ChatOpenAI from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.callbacks import get_openai_callback from langchain.chains.conversation.memory import ConversationSummaryBufferMemory from langchain.memory import ConversationBufferWindowMemory from langchain.agents import Tool, AgentExecutor, load_tools, ConversationalAgent, ConversationalChatAgent, initialize_agent, AgentType from langchain.text_splitter import TokenTextSplitter from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate, ) from langchain.schema import ( AgentAction, AIMessage, BaseMessage, BaseOutputParser, HumanMessage, ) from typing import Any, List, Optional, Sequence, Tuple from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents.conversational_chat.output_parser import ConvoOutputParser from langchain.agents.conversational_chat.prompt import ( PREFIX, SUFFIX, TEMPLATE_TOOL_RESPONSE, ) from langchain.agents.utils import validate_tools_single_input from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import BaseCallbackManager from langchain.chains import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.chat import ( ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, ) from langchain.schema import ( AgentAction, AIMessage, BaseMessage, BaseOutputParser, HumanMessage, ) from langchain.tools.base import BaseTool from constants import ( ORGANIC_RESULTS_ASK_TOOL_DESCRIPTION, QA_WEBPAGE_ASK_TOOL_DESCRIPTION, IMAGE_SEARCH_ASK_TOOL_DESCRIPTION, RECOGNIZE_IMAGE_ASK_TOOL_DESCRIPTION, SUMMARIZE_WEBPAGE_ASK_TOOL_DESCRIPTION, QA_WEBPAGE_CHAT_TOOL_DESCRIPTION, IMAGE_SEARCH_CHAT_TOOL_DESCRIPTION, ORGANIC_RESULTS_CHAT_TOOL_DESCRIPTION, RECOGNIZE_IMAGE_CHAT_TOOL_DESCRIPTION, SUMMARIZE_WEBPAGE_CHAT_TOOL_DESCRIPTION, get_ask_prefix, get_ask_custom_format_instructions, get_ask_suffix, get_chat_prefix, get_chat_custom_format_instructions, get_chat_suffix, get_thread_namer_prompt, FEATURES, ) from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import BaseChatPromptTemplate from langchain import SerpAPIWrapper, LLMChain from langchain.chat_models import ChatOpenAI from typing import List, Union from langchain.schema import AgentAction, AgentFinish, HumanMessage import re from getpass import getpass from langchain.prompts.chat import BaseChatPromptTemplate from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManager, AsyncCallbackManagerForChainRun, CallbackManager, CallbackManagerForChainRun, Callbacks, ) from langchain.chains.base import Chain from langchain.input import get_colored_text from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain.schema import LLMResult, PromptValue GOOGLE_API_KEY = os.getenv("GOOGLE_API_TOKEN") GOOGLE_CSE_ID = os.getenv("GOOGLE_CSE_ID") DISCORD_TOKEN = os.getenv("DISCORD_TOKEN") # load discord app token GUILD_ID = os.getenv("GUILD_ID") # load dev guild SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY") NEWS_API_KEY = os.getenv("NEWS_API_KEY") WOLFRAM_ALPHA_APPID = os.getenv("WOLFRAM_ALPHA_APPID") DATABASE_URL = os.getenv("DATABASE_URL") tools = [] """ tools.append(Tool( name = "Organic Results", func=dummy_sync_function, coroutine=get_organic_results, description=ORGANIC_RESULTS_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Summarize Webpage", func=dummy_sync_function, coroutine=parse_summary_webpage_input, description=SUMMARIZE_WEBPAGE_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Q&A Webpage", func=dummy_sync_function, coroutine=parse_qa_webpage_input, description=QA_WEBPAGE_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Recognize Image", func=dummy_sync_function, coroutine=parse_blip_recognition, description=RECOGNIZE_IMAGE_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Image Search", func=dummy_sync_function, coroutine=get_image_from_search, description=IMAGE_SEARCH_ASK_TOOL_DESCRIPTION, )) """ # Set up the base template template = """Complete the objective as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question These were previous tasks you completed: Begin! Question: {input} {agent_scratchpad}""" logical_llm = ChatOpenAI( openai_api_key="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", temperature=0, verbose=False, #callback_manager=manager, request_timeout=600, ) ask_llm = ChatOpenAI( temperature=0.5, model_name="gpt-3.5-turbo", openai_api_key="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", request_timeout=600, verbose=False, #callback_manager=manager, #max_tokens=max_tokens, ) async def parse_qa_webpage_input(url_comma_question): a, b = url_comma_question.split(",") answer = await question_answer_webpage(a, b, llm=logical_llm) return f"{answer}\n" async def parse_summary_webpage_input(url): summary = await summarize_webpage(url, llm=logical_llm) return summary async def parse_blip_recognition(url_comma_question): a, b = url_comma_question.split(",") output = await get_full_blip(image_url=a, question=b) return output attachment_text = "" file_placeholder = "" k_limit = 3 # Set up a prompt template class CustomPromptTemplate(BaseChatPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format_messages(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools]) formatted = self.template.format(**kwargs) return [HumanMessage(content=formatted)] class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) class CustomConversationalChatAgent(Agent): """An agent designed to hold a conversation in addition to using tools.""" output_parser: AgentOutputParser = Field(default_factory=ConvoOutputParser) template_tool_response: str = TEMPLATE_TOOL_RESPONSE @classmethod def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser: return ConvoOutputParser() @property def _agent_type(self) -> str: raise NotImplementedError @property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: super()._validate_tools(tools) validate_tools_single_input(cls.__name__, tools) @classmethod def create_prompt( cls, tools: Sequence[BaseTool], system_message: str = PREFIX, human_message: str = SUFFIX, input_variables: Optional[List[str]] = None, output_parser: Optional[BaseOutputParser] = None, ) -> BasePromptTemplate: tool_strings = "\n".join( [f"> {tool.name}: {tool.description}" for tool in tools] ) tool_names = ", ".join([tool.name for tool in tools]) _output_parser = output_parser or cls._get_default_output_parser() format_instructions = human_message.format( format_instructions=_output_parser.get_format_instructions() ) final_prompt = format_instructions.format( tool_names=tool_names, tools=tool_strings ) if input_variables is None: input_variables = ["input", "chat_history", "agent_scratchpad"] messages = [ SystemMessagePromptTemplate.from_template(system_message), MessagesPlaceholder(variable_name="chat_history"), HumanMessagePromptTemplate.from_template(final_prompt), MessagesPlaceholder(variable_name="agent_scratchpad"), ] return ChatPromptTemplate(input_variables=input_variables, messages=messages) def _construct_scratchpad( self, intermediate_steps: List[Tuple[AgentAction, str]] ) -> List[BaseMessage]: """Construct the scratchpad that lets the agent continue its thought process.""" thoughts: List[BaseMessage] = [] for action, observation in intermediate_steps: thoughts.append(AIMessage(content=action.log)) human_message = HumanMessage( content=self.template_tool_response.format(observation=observation) ) thoughts.append(human_message) return thoughts @classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, system_message: str = PREFIX, human_message: str = SUFFIX, input_variables: Optional[List[str]] = None, **kwargs: Any, ) -> Agent: """Construct an agent from an LLM and tools.""" cls._validate_tools(tools) _output_parser = output_parser or cls._get_default_output_parser() prompt = cls.create_prompt( tools, system_message=system_message, human_message=human_message, input_variables=input_variables, output_parser=_output_parser, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] return cls( llm_chain=llm_chain, allowed_tools=tool_names, output_parser=_output_parser, **kwargs, ) output_parser = CustomOutputParser() memory = ConversationBufferWindowMemory( k=k_limit, #return_messages=True, memory_key="chat_history", return_messages=True, ) prompt = CustomPromptTemplate( template=template, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps", "agent_scratchpad"] ) # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=ask_llm, prompt=prompt, memory=memory) agent = CustomConversationalChatAgent( llm_chain=llm_chain, output_parser=output_parser, ) agent_executor = AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=True ) """ while True: prompt = input("User: ") reply = agent_executor.run(prompt) print(f"Agent: {reply}") """ from langchain.chat_models import ChatOpenAI from langchain.schema import ( HumanMessage, ) from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler chat = ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0, openai_api_key="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") async def print_stream(): resp = await (["Tell me a joke."]) for response in resp: print(response) print("Stream has ended.") # Run the async function asyncio.run(print_stream())
[ "agent_scratchpad", "input", "intermediate_steps", "Complete the objective as best you can. You have access to the following tools:\n\n{tools}\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nThese were previous tasks you completed:\n\n\n\nBegin!\n\nQuestion: {input}\n{agent_scratchpad}" ]
2024-01-10
gutbash/gpt-iva-cord
output_parser.py
import re from typing import Union from langchain.agents.agent import AgentOutputParser from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS from langchain.schema import AgentAction, AgentFinish, OutputParserException class ConvoOutputParser(AgentOutputParser): ai_prefix: str = "Iva" def get_format_instructions(self) -> str: return FORMAT_INSTRUCTIONS def parse(self, text: str) -> Union[AgentAction, AgentFinish]: if f"{self.ai_prefix}:" in text: return AgentFinish( {"output": text.split(f"{self.ai_prefix}:")[-1].strip()}, text ) regex = r"(?s)Action: (.*?)[\n]*Action Input: (.*)" match = re.search(regex, text) if not match: raise OutputParserException(f"Could not parse LLM output: `{text}`") action = match.group(1) action_input = match.group(2) return AgentAction(action.strip(), action_input.strip(" ").strip('"'), text) @property def _type(self) -> str: return "conversational"
[]
2024-01-10
gutbash/gpt-iva-cord
utils~doc_utils.py
from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Tuple from pydantic import Field from langchain.chains.base import Chain from langchain.docstore.document import Document from langchain.text_splitter import RecursiveCharacterTextSplitter, TextSplitter from langchain.chains.combine_documents.base import BaseCombineDocumentsChain class AnalyzeDocumentChain(Chain): """Chain that splits documents, then analyzes it in pieces.""" input_key: str = "input_document" #: :meta private: output_key: str = "output_text" #: :meta private: text_splitter: TextSplitter = Field(default_factory=RecursiveCharacterTextSplitter) combine_docs_chain: BaseCombineDocumentsChain @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [self.input_key] @property def output_keys(self) -> List[str]: """Return output key. :meta private: """ return [self.output_key] def _call(self, inputs: Dict[str, Any]) -> Dict[str, str]: document = inputs[self.input_key] docs = self.text_splitter.create_documents([document]) # Other keys are assumed to be needed for LLM prediction other_keys = {k: v for k, v in inputs.items() if k != self.input_key} other_keys[self.combine_docs_chain.input_key] = docs return self.combine_docs_chain(other_keys, return_only_outputs=True) async def _acall(self, inputs: Dict[str, Any]) -> Dict[str, str]: document = inputs[self.input_key] docs = self.text_splitter.create_documents([document]) # Other keys are assumed to be needed for LLM prediction other_keys = {k: v for k, v in inputs.items() if k != self.input_key} other_keys[self.combine_docs_chain.input_key] = docs # Assuming combine_docs_chain has an async __call__ method combined_docs = await self.combine_docs_chain(other_keys, return_only_outputs=True) print("COMBINED DOCS") return combined_docs
[]
2024-01-10
gutbash/gpt-iva-cord
iva.py
import discord from discord import app_commands import discord.ext.commands import discord.ext.tasks from utils.log_utils import colors from utils.redis_utils import save_pickle_to_redis, load_pickle_from_redis from utils.postgres_utils import fetch_key, fetch_keys_table, upsert_key, delete_key from utils.tool_utils import dummy_sync_function from tools import ( get_image_from_search, get_organic_results, get_shopping_results, question_answer_webpage, summarize_webpage, get_full_blip, view_webpage_window, ) import sys import asyncio from io import StringIO from typing import Dict, Optional from pydantic import BaseModel, Field import time import asyncio import os import openai import datetime from transformers import GPT2TokenizerFast import re import requests import itertools import pydot import PyPDF2 import io import textwrap import chardet import aiohttp import logging import subprocess import pandas as pd from docx import Document from langchain.chat_models import ChatOpenAI from langchain.llms import OpenAI from langchain.chains.llm import LLMChain from langchain.callbacks import get_openai_callback from langchain.chains.conversation.memory import ConversationSummaryBufferMemory from langchain.memory.buffer_window import ConversationBufferWindowMemory from langchain.memory.token_buffer import ConversationTokenBufferMemory from langchain.agents import Tool from langchain.agents.conversational.base import ConversationalAgent from langchain.agents.agent import AgentExecutor from output_parser import ConvoOutputParser from langchain.text_splitter import TokenTextSplitter from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate, ) from constants import ( ORGANIC_RESULTS_ASK_TOOL_DESCRIPTION, QA_WEBPAGE_ASK_TOOL_DESCRIPTION, WEBPAGE_WINDOW_ASK_TOOL_DESCRIPTION, IMAGE_SEARCH_ASK_TOOL_DESCRIPTION, RECOGNIZE_IMAGE_ASK_TOOL_DESCRIPTION, SUMMARIZE_WEBPAGE_ASK_TOOL_DESCRIPTION, PYTHON_REPL_ASK_TOOL_DESCRIPTION, QA_WEBPAGE_CHAT_TOOL_DESCRIPTION, IMAGE_SEARCH_CHAT_TOOL_DESCRIPTION, ORGANIC_RESULTS_CHAT_TOOL_DESCRIPTION, RECOGNIZE_IMAGE_CHAT_TOOL_DESCRIPTION, SUMMARIZE_WEBPAGE_CHAT_TOOL_DESCRIPTION, get_ask_prefix, get_ask_custom_format_instructions, get_ask_suffix, get_chat_prefix, get_chat_custom_format_instructions, get_chat_suffix, get_thread_namer_prompt, FEATURES, ) GOOGLE_API_KEY = os.getenv("GOOGLE_API_TOKEN") GOOGLE_CSE_ID = os.getenv("GOOGLE_CSE_ID") DISCORD_TOKEN = os.getenv("DISCORD_TOKEN") # load discord app token GUILD_ID = os.getenv("GUILD_ID") # load dev guild SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY") NEWS_API_KEY = os.getenv("NEWS_API_KEY") WOLFRAM_ALPHA_APPID = os.getenv("WOLFRAM_ALPHA_APPID") DATABASE_URL = os.getenv("DATABASE_URL") logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') tokenizer = GPT2TokenizerFast.from_pretrained("gpt2") # initialize tokenizer intents = discord.Intents.default() # declare intents intents.message_content = True intents.presences = False intents.members = False client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) active_users = {} # dict of lists active_names = {} # dict of strings @client.event async def on_ready(): await fetch_keys_table() await tree.sync() logging.info(f"Registered {len(client.guilds)} guilds.") logging.info(f"Logged in as @{client.user.name}.") @client.event async def on_guild_join(guild): logging.info(f"Client added to guild {guild}.") await tree.sync(guild=guild) @client.event async def on_message(message): if message.author == client.user: return agent_mention = client.user.mention if "<@&1053339601449779383>" in message.content or agent_mention in message.content: global active_users global active_names active_users = await load_pickle_from_redis('active_users') chat_mems = await load_pickle_from_redis('chat_mems') # Get the current timestamp timestamp = datetime.datetime.now() time = timestamp.strftime(r"%Y-%m-%d %I:%M:%S") itis = timestamp.strftime(r"%B %d, %Y") clock = timestamp.strftime(r"%I:%M %p") channel_id = message.channel.id if channel_id not in chat_mems: chat_mems[channel_id] = None if channel_id not in active_users: active_users[channel_id] = [] guild_name = message.guild if guild_name == None: guild_name = "DM" bot = client.user.display_name user_name = message.author.name id = message.author.id user_mention = message.author.mention prompt = message.content attachments = message.attachments openai_key = "" prompt = prompt.replace("<@1050437164367880202>", "") prompt = prompt.strip() attachment_text = '' file_placeholder = '' blip_text = '' async with message.channel.typing(): result = await fetch_key(id) user_settings = await load_pickle_from_redis('user_settings') chat_model = user_settings.get(id, {}).get('model', 'gpt-3.5-turbo') #temperature = user_settings.get(id, {}).get('temperature', 0.5) temperature = 0.5 if chat_model == "gpt-3.5-turbo-0613": chat_model = "gpt-3.5-turbo" max_tokens = 4096 if chat_model == "gpt-4": max_tokens = 8192 if result != None: openai.api_key=result openai_key=result else: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {user_mention} Use `/setup` to register API key first or `/help` for more info. You can find your API key at [openai.com](https://beta.openai.com).', color=discord.Color.dark_theme()) await message.channel.send(embed=embed) return text_splitter = TokenTextSplitter() logical_llm = ChatOpenAI( openai_api_key=openai_key, temperature=0, verbose=True, #callback_manager=manager, request_timeout=600, ) async def parse_organic_results_input(url_comma_question): #a, b = url_comma_question.split(",", maxsplit=1) #answer = await get_organic_results(query=a, recency_days=int(b), llm=logical_llm) answer = await get_organic_results(query=url_comma_question, recency_days=None, llm=logical_llm) return f"{answer}" async def parse_qa_webpage_input(url_comma_question): a, b = url_comma_question.split(",", maxsplit=1) answer = await question_answer_webpage(url=a, question=b, llm=logical_llm) return f"{answer}\n" async def parse_summary_webpage_input(url): summary = await summarize_webpage(url, llm=logical_llm) return summary async def parse_blip_recognition(url_comma_question): a, b = url_comma_question.split(",", maxsplit=1) output = await get_full_blip(image_url=a, question=b) return output async def parse_view_webpage_input(url_comma_page_index): a, b = url_comma_page_index.split(",", maxsplit=1) output = await view_webpage_window(url=a, span_index=int(b)) return output # STRINGIFY ACTIVE USERS if f"{user_name} ({user_mention})" not in active_users[channel_id]: active_users[channel_id].append(f"{user_name} ({user_mention})") active_names[channel_id] = ", ".join(active_users[channel_id]) try: files = [] if chat_model != "text-davinci-003": chat_llm = ChatOpenAI( temperature=temperature, model_name=chat_model, openai_api_key=openai_key, request_timeout=600, verbose=True, ) else: chat_llm = OpenAI( temperature=temperature, model_name=chat_model, openai_api_key=openai_key, request_timeout=600, verbose=True, ) tools = [] def dummy_sync_function(tool_input: str) -> str: raise NotImplementedError("This tool only supports async") tools.append(Tool( name = "Search", func=dummy_sync_function, coroutine=parse_organic_results_input, description=ORGANIC_RESULTS_CHAT_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Summarize Webpage", func=dummy_sync_function, coroutine=parse_summary_webpage_input, description=SUMMARIZE_WEBPAGE_CHAT_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Query Webpage", func=dummy_sync_function, coroutine=parse_qa_webpage_input, description=QA_WEBPAGE_CHAT_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Webpage", func=dummy_sync_function, coroutine=parse_view_webpage_input, description=WEBPAGE_WINDOW_ASK_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Vision", func=dummy_sync_function, coroutine=parse_blip_recognition, description=RECOGNIZE_IMAGE_CHAT_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Images", func=dummy_sync_function, coroutine=get_image_from_search, description=IMAGE_SEARCH_CHAT_TOOL_DESCRIPTION, )) """ tool_names = [tool.name for tool in tools] prefix = await get_chat_prefix(active_names=active_names.get(channel_id, ''), itis=itis) custom_format_instructions = await get_chat_custom_format_instructions(tool_names=tool_names, user_name=user_name) suffix = await get_chat_suffix() if attachments != []: for file in attachments: file_type = file.content_type attachment_bytes = await file.read() file_name = file.filename with open(f'{file_name}', 'wb') as f: f.write(attachment_bytes) if file_type in ('image/jpeg', 'image/jpg', 'image/png'): blip_text += f"\n\n{file_name} attached and saved to working directory: {file.url}" file_placeholder += f"\n\n:frame_photo: **{file_name}**" elif "text/plain" in file_type: #txt # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{attachment_bytes.decode(encoding)}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "application/vnd.openxmlformats-officedocument.wordprocessingml.document" in file_type: #docx file_like_object = io.BytesIO(attachment_bytes) doc = Document(file_like_object) full_text = [] for para in doc.paragraphs: full_text.append(para.text) raw_text = "\n".join(full_text) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{raw_text}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "application/pdf" in file_type: #pdf pdf_file = io.BytesIO(attachment_bytes) pdf_reader = PyPDF2.PdfReader(pdf_file) pdf_content = "" for page in range(len(pdf_reader.pages)): page_text = pdf_reader.pages[page].extract_text() # Replace multiple newlines with a single space page_text = re.sub(r'\n+', ' ', page_text) pdf_content += page_text file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + pdf_content, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{pdf_content[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{pdf_content}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "text/csv" in file_type: #csv try: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) data = pd.read_csv(file_name) attachment_text += f"\n\n{file_name} has been saved to the working directory. Here is a preview of the file head:\n--- {file_name} ---\n\n{data.head()}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" except: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" else: try: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{attachment_bytes.decode(encoding)}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" except: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {user_mention} the attachment\'s file type is unknown. consider converting it to plain text such as `.txt`.', color=discord.Color.dark_theme()) await message.channel.send(embed=embed) return guild_prompt = ConversationalAgent.create_prompt( tools=tools, prefix=textwrap.dedent(prefix).strip(), suffix=textwrap.dedent(suffix).strip(), format_instructions=textwrap.dedent(custom_format_instructions).strip(), input_variables=["input", "chat_history", "agent_scratchpad"], ai_prefix = f"Iva", human_prefix = f"", ) if chat_mems[channel_id] != None: guild_memory = chat_mems[channel_id] guild_memory.max_token_limit = 2000 guild_memory.ai_prefix = f"Iva" guild_memory.human_prefix = f"" else: guild_memory = ConversationSummaryBufferMemory( llm=chat_llm, max_token_limit=2000, memory_key="chat_history", input_key="input", ai_prefix = f"Iva", human_prefix = f"", ) llm_chain = LLMChain( llm=chat_llm, verbose=True, prompt=guild_prompt, ) output_parser = ConvoOutputParser( ai_prefix="Iva", ) agent = ConversationalAgent( llm_chain=llm_chain, tools=tools, verbose=True, ai_prefix=f"Iva", llm_prefix=f"Iva", output_parser=output_parser, ) agent_chain = AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=True, memory=guild_memory, ai_prefix=f"Iva", llm_prefix=f"Iva", max_execution_time=600, #max_iterations=3, #early_stopping_method="generate", #return_intermediate_steps=False, ) try: reply = await agent_chain.arun(input=f"{user_name} ({user_mention}): {prompt}{attachment_text}") except Exception as e: if str(e).startswith("Could not parse LLM output:"): reply = str(e).replace("Could not parse LLM output: `", "") reply = reply.replace("Thought: Do I need to use a tool? No", "") reply = reply.strip("`") mem_list = guild_memory.chat_memory.messages extend_mems_list = [ HumanMessage( content=prompt, additional_kwargs={}, ), AIMessage( content=reply, additional_kwargs={}, )] mem_list.extend(extend_mems_list) else: logging.error(e) embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {user_mention} `{type(e).__name__}` {e}\n\nuse `/help` or seek https://discord.com/channels/1053335631159377950/1053336180692897943 if the issue persists.') await message.channel.send(embed=embed) return except Exception as e: logging.error(e) embed = discord.Embed(description=f'error', color=discord.Color.dark_theme()) await message.channel.send(embed=embed) return try: reply = reply.replace("Iva: ", "") reply = reply.replace("Do I need to use a tool? No", "") if len(reply) > 2000: embed = discord.Embed(description=reply, color=discord.Color.dark_theme()) await message.channel.send(embed=embed) return else: await message.channel.send(content=f"{reply}", files=files) chat_mems[channel_id] = guild_memory await save_pickle_to_redis('active_users', active_users) await save_pickle_to_redis('chat_mems', chat_mems) except Exception as e: logging.error(e) embed = discord.Embed(description=f'error', color=discord.Color.dark_theme()) await message.channel.send(embed=embed) return return class Opt(discord.ui.View): def __init__(self, key: str): super().__init__(timeout=60 * 60 * 24 * 365) self.value = None self.key = key async def on_timeout(self) -> None: for item in self.children: item.disabled = True await self.message.edit(view=self) @discord.ui.button(label="Agree and Continue", emoji="<:ivaup:1101609056604524594>", style=discord.ButtonStyle.grey) async def agree(self, interaction: discord.Interaction, button: discord.ui.Button): user_id = interaction.user.id mention = interaction.user.mention await upsert_key(str(user_id), self.key) embed = discord.Embed(description=f"<:ivathumbsup:1051918474299056189> **Key registered for {mention}. Welcome to Iva!**", color=discord.Color.dark_theme()) await interaction.response.edit_message(embed=embed, delete_after=10, view=None) return @discord.ui.button(label="Disagree", emoji="<:ivadown:1101609054729666610>", style=discord.ButtonStyle.grey) async def disagree(self, interaction: discord.Interaction, button: discord.ui.Button): user_id = interaction.user.id mention = interaction.user.mention await delete_key(user_id) embed = discord.Embed(description=f"<:ivathumbsup:1051918474299056189> **You have opted out.**", color=discord.Color.dark_theme()) await interaction.response.edit_message(embed=embed, delete_after=10, view=None) return class Menu(discord.ui.View): def __init__(self): super().__init__(timeout=60 * 60 * 24 * 365) self.value = None async def on_timeout(self) -> None: # Step 2 for item in self.children: item.disabled = True # Step 3 await self.message.edit(view=self) @discord.ui.button(emoji="<:ivadelete:1095559772754952232>", style=discord.ButtonStyle.grey) async def delete(self, interaction: discord.Interaction, button: discord.ui.Button): guild_id = interaction.guild_id user_id = interaction.user.id channel_id = interaction.channel.id mention = interaction.user.mention ask_mems = await load_pickle_from_redis('ask_mems') if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["user_id"] is not None: original_user_id = ask_mems[channel_id][user_id]["user_id"] else: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} You do not own this context line', color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return if original_user_id != user_id: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} You do not own this context line', color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return else: try: if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["memory"] is not None: memory = ask_mems[channel_id][user_id]["memory"] memory.chat_memory.messages = memory.chat_memory.messages[:-2] await save_pickle_to_redis('ask_mems', ask_mems) except Exception as e: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} `{type(e).__name__}` {e}\n\nuse `/help` or seek https://discord.com/channels/1053335631159377950/1053336180692897943 if the issue persists.') await interaction.channel.send(content=None, embed=embed) embed = discord.Embed(description=f'<:ivadelete:1095559772754952232>', color=discord.Color.dark_theme()) await interaction.message.edit(content=None, embed=embed, view=None, delete_after=5) return @discord.ui.button(emoji="<:ivareset:1051691297443950612>", style=discord.ButtonStyle.grey) async def reset(self, interaction: discord.Interaction, button: discord.ui.Button): guild_id = interaction.guild_id channel_id = interaction.channel.id user_id = interaction.user.id mention = interaction.user.mention ask_mems = await load_pickle_from_redis('ask_mems') if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["user_id"] is not None: original_user_id = ask_mems[channel_id][user_id]["user_id"] else: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} You do not own this context line', color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return if original_user_id != user_id: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} You do not own this context line', color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return else: if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["memory"] is not None: ask_mems[channel_id][user_id]["memory"] = None if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["last_message_id"] is not None: ask_mems[channel_id][user_id]["last_message_id"] = None await save_pickle_to_redis('ask_mems', ask_mems) embed = discord.Embed(description="<:ivareset:1051691297443950612>", color=discord.Color.dark_theme()) button.disabled = True embeds = interaction.message.embeds attachments = interaction.message.attachments embeds.append(embed) await interaction.message.edit(view=None, embeds=embeds, attachments=attachments) #await interaction.channel.send(embed=embed) @tree.command(name = "iva", description="write a prompt") @app_commands.describe(prompt = "prompt", file_one = "file one", file_two = "file two", file_three = "file three") async def iva(interaction: discord.Interaction, prompt: str, file_one: discord.Attachment = None, file_two: discord.Attachment = None, file_three: discord.Attachment = None): start_time = time.monotonic() guild_id = interaction.guild_id guild_name = interaction.guild user_id = interaction.user.id user = interaction.user channel_id = interaction.channel.id mention = interaction.user.mention bot = client.user.display_name user_name = interaction.user.name channel = interaction.channel try: await interaction.response.defer() # fetch the row with the given id result = await fetch_key(user_id) openai_key = "" if result != None: openai.api_key=result openai_key=result else: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} Use `/setup` to register API key first or `/help` for more info. You can find your API key at [openai.com](https://beta.openai.com).', color=discord.Color.dark_theme()) await interaction.followup.send(embed=embed, ephemeral=True) return if isinstance(interaction.channel, discord.TextChannel): followup_message = await interaction.followup.send(content=channel.jump_url) await followup_message.delete() try: thread_namer = ChatOpenAI(temperature=1.0, openai_api_key=openai_key) template = await get_thread_namer_prompt(user_name) system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_template = f"\"{{text}}\"" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) thread_namer_chain = LLMChain(llm=thread_namer, prompt=chat_prompt) thread_name = await thread_namer_chain.arun(f"{prompt}") thread_name = thread_name.strip("'").replace('.', '').replace('"', '').replace("Title: ", "") thread_name = thread_name[:100] #s lice if larger than 100 chars channel = await interaction.channel.create_thread( type=discord.ChannelType.public_thread, name=thread_name, ) await channel.add_user(user) channel_id = channel.id thinking_message = await channel.send(content="<a:ivaloading:1102305649246867561> iva is thinking...") except Exception as e: logging.error(e) embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} `{type(e).__name__}` {e}\n\nuse `/help` or seek https://discord.com/channels/1053335631159377950/1053336180692897943 if the issue persists.') await interaction.followup.send(embed=embed, ephemeral=True) return default_user_data = { "last_message_id": None, "user_id": None, "memory": None, } user_settings = await load_pickle_from_redis('user_settings') ask_mems = await load_pickle_from_redis('ask_mems') ask_mems.setdefault(channel_id, {}).setdefault(user_id, default_user_data) chat_model = user_settings.get(user_id, {}).get('model', 'gpt-3.5-turbo') temperature = user_settings.get(user_id, {}).get('temperature', 0.5) if chat_model == "gpt-3.5-turbo-0613": chat_model = "gpt-3.5-turbo" if chat_model == "gpt-4": max_tokens = 8192 elif chat_model == "gpt-3.5-turbo": max_tokens = 4096 elif chat_model == "gpt-3.5-turbo-16k": max_tokens = 16384 else: max_tokens = 4096 # Get the current timestamp timestamp = datetime.datetime.now() itis = timestamp.strftime(r"%B %d, %Y") view = Menu() logical_llm = ChatOpenAI( openai_api_key=openai_key, temperature=0, verbose=True, #model_name=chat_model, #callback_manager=manager, request_timeout=600, ) async def parse_organic_results_input(url_comma_question): #a, b = url_comma_question.split(",", maxsplit=1) #answer = await get_organic_results(query=a, recency_days=int(b), llm=logical_llm) answer = await get_organic_results(query=url_comma_question, recency_days=None, llm=logical_llm) return f"{answer}" async def parse_qa_webpage_input(url_comma_question): a, b = url_comma_question.split(",", maxsplit=1) answer = await question_answer_webpage(url=a, question=b, llm=logical_llm) return f"{answer}\n" async def parse_summary_webpage_input(url): summary = await summarize_webpage(url, llm=logical_llm) return summary async def parse_blip_recognition(url_comma_question): a, b = url_comma_question.split(",", maxsplit=1) output = await get_full_blip(image_url=a, question=b) return output async def parse_view_webpage_input(url_comma_page_index): url_comma_page_index = url_comma_page_index.strip("[").strip("]") url_comma_page_index = url_comma_page_index.strip() a, b = url_comma_page_index.split(",", maxsplit=1) output = await view_webpage_window(url=a, span_index=int(b)) return output tools = [] embeds = [] files = [] embeds_overflow = [] files_overflow = [] file_count=0 class PythonREPL(BaseModel): """Simulates a standalone Python REPL.""" globals: Optional[Dict] = Field(default_factory=dict, alias="_globals") locals: Optional[Dict] = Field(default_factory=dict, alias="_locals") def run(self, command: str) -> str: logging.info("using sync run repl") #command = autopep8.fix_code(command, options={"aggressive": 2}) """Run command with own globals/locals and returns anything printed.""" old_stdout = sys.stdout sys.stdout = mystdout = StringIO() try: exec(command, self.globals, self.locals) sys.stdout = old_stdout output = mystdout.getvalue() except Exception as e: sys.stdout = old_stdout output = str(e) return output async def arun(self, command: str) -> str: logging.info("using async run repl") #command = autopep8.fix_code(command, options={"aggressive": 2}) """Run command (sync or async) with own globals/locals and returns anything printed.""" old_stdout = sys.stdout sys.stdout = mystdout = StringIO() async def run_sync_code(): loop = asyncio.get_running_loop() return await loop.run_in_executor(None, self.run, command) async def run_async_code(): exec( f"async def __arun_inner(scope):\n" f" async with scope:\n" f" {command}\n", self.globals, self.locals, ) coroutine = self.locals["__arun_inner"](asyncio.get_event_loop()) await coroutine try: if "async " in command: logging.info("detected async code") await run_async_code() else: logging.info("detected sync code") await run_sync_code() sys.stdout = old_stdout output = mystdout.getvalue() except Exception as e: logging.error(e) sys.stdout = old_stdout output = str(e) return output async def python_repl(command): command = command.strip().replace("```python", "").replace("```py", "").strip("```").replace(".show()", ".savefig('output.png')") if "!pip" in command: pip_install_lines = re.findall(r'^!pip install .*\n?', command, re.MULTILINE) command = re.sub(r'^!pip install .*\n?', '', command, flags=re.MULTILINE) for pip in pip_install_lines: logging.info(f"PIP INSTALL COMMAND: {pip}") # Handle pip install package = pip.strip().split(' ')[-1] result = subprocess.check_call([sys.executable, "-m", "pip", "install", package]) if result == 0: # if the pip install command was successful await python_repl(command) return ''' command = f"""try: {command} except Exception as e: print(str(e))""" ''' logging.info(f"SANITIZED COMMAND: {command}") repl = PythonREPL() # Get the list of files before running the command before_files = set(os.listdir()) try: output = await repl.arun(command) except Exception as e: logging.error(e) # Get the list of files after running the command after_files = set(os.listdir()) logging.info(after_files) # Get the list of created files created_files = list(after_files - before_files) for file in created_files: if file.startswith("."): continue else: try: output += f"{file} attached. " logging.info(f"FILE ATTACHED {file}") files.append(discord.File(fp=file)) os.remove(file) except IsADirectoryError as e: continue return output tools.append(Tool( name = "Search", func=dummy_sync_function, coroutine=parse_organic_results_input, description=ORGANIC_RESULTS_ASK_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Summarize Webpage", func=dummy_sync_function, coroutine=parse_summary_webpage_input, description=SUMMARIZE_WEBPAGE_ASK_TOOL_DESCRIPTION, )) """ """ tools.append(Tool( name = "Query Webpage", func=dummy_sync_function, coroutine=parse_qa_webpage_input, description=QA_WEBPAGE_ASK_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Webpage", func=dummy_sync_function, coroutine=parse_view_webpage_input, description=WEBPAGE_WINDOW_ASK_TOOL_DESCRIPTION, )) """ tools.append(Tool( name = "Python REPL", func=dummy_sync_function, coroutine=python_repl, description=PYTHON_REPL_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Vision", func=dummy_sync_function, coroutine=parse_blip_recognition, description=RECOGNIZE_IMAGE_ASK_TOOL_DESCRIPTION, )) tools.append(Tool( name = "Images", func=dummy_sync_function, coroutine=get_image_from_search, description=IMAGE_SEARCH_ASK_TOOL_DESCRIPTION, )) """ tool_names = [tool.name for tool in tools] prefix = await get_ask_prefix(itis=itis) custom_format_instructions = await get_ask_custom_format_instructions(tool_names=tool_names) suffix = await get_ask_suffix() blip_text = "" attached_files = [file_one, file_two, file_three] attachment_text = "" file_placeholder = "" for file in attached_files: if file != None: attachment_bytes = await file.read() file_type = file.content_type file_name = file.filename with open(f'{file_name}', 'wb') as f: f.write(attachment_bytes) files.append(discord.File(f"{file_name}")) file_count += 1 if file_type in ('image/jpeg', 'image/jpg', 'image/png'): blip_text += f"\n\n{file_name} attached and saved to working directory: {file.url}" file_placeholder += f"\n\n:frame_photo: **{file_name}**" elif "text/plain" in file_type: #txt # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{attachment_bytes.decode(encoding)}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "application/vnd.openxmlformats-officedocument.wordprocessingml.document" in file_type: #docx file_like_object = io.BytesIO(attachment_bytes) doc = Document(file_like_object) full_text = [] for para in doc.paragraphs: full_text.append(para.text) raw_text = "\n".join(full_text) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{raw_text}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "application/pdf" in file_type: #pdf pdf_file = io.BytesIO(attachment_bytes) pdf_reader = PyPDF2.PdfReader(pdf_file) pdf_content = "" for page in range(len(pdf_reader.pages)): page_text = pdf_reader.pages[page].extract_text() # Replace multiple newlines with a single space page_text = re.sub(r'\n+', ' ', page_text) pdf_content += page_text file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + pdf_content, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{pdf_content[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{pdf_content}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" elif "text/csv" in file_type: #csv try: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) data = pd.read_csv(file_name) attachment_text += f"\n\n{file_name} has been saved to the working directory. Here is a preview of the file head:\n--- {file_name} ---\n\n{data.head()}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" except: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" else: try: # Detect encoding detected = chardet.detect(attachment_bytes) encoding = detected['encoding'] # Decode using the detected encoding raw_text = attachment_bytes.decode(encoding) file_tokens = len(tokenizer(prefix + custom_format_instructions + suffix + raw_text, truncation=True, max_length=12000)['input_ids']) if file_tokens >= max_tokens: attachment_text += f"\n\n{file_name} is too large for you to view, but it has still been saved to the directory if you'd like to use Python REPL to interact with it. Here is a preview of the file:\n--- {file_name} ---\n\n{raw_text[:100]} [...]" else: attachment_text += f"\n\n{file_name} has been saved to the working directory\n--- {file_name} ---\n\n{attachment_bytes.decode(encoding)}" file_placeholder += f"\n\n:page_facing_up: **{file_name}**" except: embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} the attachment\'s file type is unknown. consider converting it to plain text such as `.txt`.', color=discord.Color.dark_theme()) if isinstance(interaction.channel, discord.TextChannel): await thinking_message.edit(content=None, embed=embed) else: await interaction.followup.send(embed=embed, ephemeral=True) return try: if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["last_message_id"] is not None: original_message = await interaction.channel.fetch_message(ask_mems[channel_id][user_id]["last_message_id"]) await original_message.edit(content="⠀", view=None) except discord.errors.HTTPException as e: logging.error(e) if chat_model != "text-davinci-003": ask_llm = ChatOpenAI( temperature=temperature, model_name=chat_model, openai_api_key=openai_key, request_timeout=600, verbose=True, #callback_manager=manager, #max_tokens=max_tokens, ) else: ask_llm = OpenAI( temperature=temperature, model_name=chat_model, openai_api_key=openai_key, request_timeout=600, verbose=True, ) k_limit = 3 total_cost = None if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["memory"] is not None: memory = ask_mems[channel_id][user_id]["memory"] else: memory = ConversationTokenBufferMemory( return_messages=False, human_prefix="User", ai_prefix="Iva", llm=ask_llm, memory_key="chat_history", max_token_limit=2000, ) ask_mems[channel_id][user_id]["memory"] = None guild_prompt = ConversationalAgent.create_prompt( tools=tools, prefix=textwrap.dedent(prefix).strip(), suffix=textwrap.dedent(suffix).strip(), format_instructions=textwrap.dedent(custom_format_instructions).strip(), input_variables=["input", "chat_history", "agent_scratchpad"], ai_prefix = f"Iva", human_prefix = f"User", ) llm_chain = LLMChain( llm=ask_llm, prompt=guild_prompt, verbose=True ) output_parser = ConvoOutputParser( ai_prefix="Iva", ) agent = ConversationalAgent( llm_chain=llm_chain, allowed_tools=tool_names, ai_prefix=f"Iva", output_parser=output_parser, ) agent_chain = AgentExecutor.from_agent_and_tools( memory=memory, agent=agent, tools=tools, verbose=True, ai_prefix=f"Iva", max_execution_time=600, #max_iterations=3, #early_stopping_method="generate", #return_intermediate_steps=True, ) url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') links = url_pattern.findall(prompt) link_guidance = "" #if links: # link_guidance = " (open the link with a tool)" try: with get_openai_callback() as cb: reply = await agent_chain.arun(input=f"{prompt}{link_guidance}{blip_text}{attachment_text}") total_cost = cb.total_cost except Exception as e: if str(e).startswith("Could not parse LLM output:"): logging.error(e) reply = str(e).replace("Could not parse LLM output: `", "") reply = reply.replace("Thought: Do I need to use a tool? No", "") reply = reply.strip("`") mem_list = memory.chat_memory.messages extend_mems_list = [ HumanMessage( content=prompt, additional_kwargs={}, ), AIMessage( content=reply, additional_kwargs={}, )] mem_list.extend(extend_mems_list) else: logging.error(e) embed = discord.Embed(description=f'<:ivanotify:1051918381844025434> {mention} `{type(e).__name__}` {e}\n\nuse `/help` or seek https://discord.com/channels/1053335631159377950/1053336180692897943 if the issue persists.') if isinstance(interaction.channel, discord.TextChannel): await thinking_message.edit(content=None, embed=embed) else: await interaction.followup.send(embed=embed, ephemeral=True) return reply = reply.replace("Iva: ", "") reply = reply.replace("Do I need to use a tool? No", "") reply = reply.replace("```C#", "```cs") # Regex pattern for Markdown inline images pattern = r'\n?!\[.*?\]\(.*?\)' # Substituting the pattern with an empty string reply = re.sub(pattern, '', reply) dash_count = "" interaction_count = (len(memory.buffer)//2)-1 for i in range(interaction_count): dash_count += "-" embed = discord.Embed(description=reply, color=discord.Color.dark_theme()) file_count += 1 if '$$' in reply or '```dot' in reply: # Use the findall() method of the re module to find all occurrences of content between $$ dpi = "{200}" color = "{white}" tex_pattern = re.compile(r"\$\$(.*?)\$\$", re.DOTALL) dot_pattern = re.compile(r'```dot\s*([\s\S]*?)\s*```', re.DOTALL) tex_matches = tex_pattern.findall(reply) dot_matches = dot_pattern.finditer(reply) dot_matches = [match.group(1).strip() for match in dot_matches] non_matches = re.sub(r"```dot\s*[\s\S]*?\s*```|(\$\$|\%\%|\@\@).*?(\@\@|\%\%|\$\$)", "~~", reply, flags=re.DOTALL) non_matches = non_matches.split("~~") try: for (tex_match, dot_match, non_match) in itertools.zip_longest(tex_matches, dot_matches, non_matches): if non_match != None and non_match != "" and non_match != "\n" and non_match != "." and non_match != "\n\n" and non_match != " " and non_match != "\n> " and non_match.isspace() != True and non_match.startswith("![") != True: non_match = non_match.replace("$", "`") non_match_embed = discord.Embed(description=non_match, color=discord.Color.dark_theme()) if len(embeds) >= 9: embeds_overflow.append(non_match_embed) else: embeds.append(non_match_embed) if tex_match != None and tex_match != "" and tex_match != "\n" and tex_match != " " and tex_match.isspace() != True: tex_match = tex_match.strip() tex_match = tex_match.replace("\n", "") tex_match = tex_match.strip("$") tex_match = tex_match.split() tex_match = "%20".join(tex_match) match_embed = discord.Embed(color=discord.Color.dark_theme()) image_url = f"https://latex.codecogs.com/png.image?\dpi{dpi}\color{color}{tex_match}" img_data = requests.get(image_url, verify=False).content subfolder = 'tex' if not os.path.exists(subfolder): os.makedirs(subfolder) with open(f'{subfolder}/latex{file_count}.png', 'wb') as handler: handler.write(img_data) tex_file = discord.File(f'{subfolder}/latex{file_count}.png') match_embed.set_image(url=f"attachment://latex{file_count}.png") file_count += 1 if len(embeds) >= 9: embeds_overflow.append(match_embed) files_overflow.append(tex_file) else: embeds.append(match_embed) files.append(tex_file) if dot_match != None and dot_match != "" and dot_match != "\n" and dot_match.isspace() != True: pattern = r'((di)?graph\s+[^{]*\{)' replacement = r'\1\nbgcolor="#36393f";\nnode [fontcolor=white, color=white];\nedge [fontcolor=white, color=white];\n' dot_match = re.sub(pattern, replacement, dot_match) graphs = pydot.graph_from_dot_data(dot_match) graph = graphs[0] subfolder = 'graphviz' if not os.path.exists(subfolder): os.makedirs(subfolder) graph.write_png(f'{subfolder}/graphviz{file_count}.png') dot_file = discord.File(f'{subfolder}/graphviz{file_count}.png') match_embed = discord.Embed(color=discord.Color.dark_theme()) match_embed.set_image(url=f"attachment://graphviz{file_count}.png") file_count += 1 if len(embeds) >= 9: embeds_overflow.append(match_embed) files_overflow.append(dot_file) else: embeds.append(match_embed) files.append(dot_file) except Exception as e: logging.error(e) else: if len(reply) > 4096: try: embeds = [] substrings = [] for i in range(0, len(reply), 4096): substring = reply[i:i+4096] substrings.append(substring) for string in substrings: embed_string = discord.Embed(description=string, color=discord.Color.dark_theme()) embeds.append(embed_string) except Exception as e: logging.error(e) embed = discord.Embed(description=f'<:ivaerror:1051918443840020531> **{mention} 4096 character response limit reached. Response contains {len(reply)} characters. Use `/reset`.**', color=discord.Color.dark_theme()) if isinstance(interaction.channel, discord.TextChannel): await thinking_message.edit(content=None, embed=embed) else: await interaction.followup.send(embed=embed, ephemeral=True) else: embeds.append(embed) try: end_time = time.monotonic() word_count = len(reply.split()) elapsed_time = end_time - start_time minutes, seconds = divmod(elapsed_time, 60) elapsed_time_format = f"{int(minutes):02}:{int(seconds):02}" if total_cost is not None: prompt_embed = discord.Embed(description=f"{dash_count}→ {prompt}{file_placeholder}\n\n`{chat_model}` `{temperature}` `{round(total_cost, 3)}` `{elapsed_time_format}` `{word_count}`") else: prompt_embed = discord.Embed(description=f"{dash_count}→ {prompt}{file_placeholder}\n\n`{chat_model}` `{temperature}` `{elapsed_time_format}` `{word_count}`") embeds.insert(0, prompt_embed) if isinstance(interaction.channel, discord.TextChannel): await thinking_message.delete() initial_message = await channel.send(files=files, embeds=embeds, view=view) message_id = initial_message.id else: followup_message = await interaction.followup.send(files=files, embeds=embeds, view=view) message_id = followup_message.id if len(embeds_overflow) > 0: await channel.send(files = files_overflow, embeds=embeds_overflow) url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') links = url_pattern.findall(reply) stripped_links = [link.rstrip(',.:)]') for link in links] if len(stripped_links) > 0: stripped_links = list(set(stripped_links)) formatted_links = "\n".join(stripped_links) await channel.send(content=formatted_links) ask_mems[channel_id][user_id]["last_message_id"] = message_id ask_mems[channel_id][user_id]["user_id"] = user_id ask_mems[channel_id][user_id]["memory"] = memory await save_pickle_to_redis('ask_mems', ask_mems) return except Exception as e: logging.error(e, stack_info=True) except discord.errors.NotFound as e: logging.error(e, stack_info=True) @tree.command(name = "reset", description="start a new conversation") async def reset(interaction): channel_id = interaction.channel_id guild_id = interaction.guild_id user_id = interaction.user.id active_users = await load_pickle_from_redis('active_users') ask_mems = await load_pickle_from_redis('ask_mems') chat_mems = await load_pickle_from_redis('chat_mems') try: if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["last_message_id"] is not None: original_message = await interaction.channel.fetch_message(ask_mems[channel_id][user_id]["last_message_id"]) await original_message.edit(content="⠀", view=None) except discord.errors.HTTPException as e: logging.error(e) if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["last_message_id"] is not None: ask_mems[channel_id][user_id]["last_message_id"] = None if channel_id in ask_mems and user_id in ask_mems[channel_id] and ask_mems[channel_id][user_id]["memory"] is not None: ask_mems[channel_id][user_id]["memory"] = None chat_mems[channel_id] = None active_users[channel_id] = [] await save_pickle_to_redis('ask_mems', ask_mems) await save_pickle_to_redis('active_users', active_users) await save_pickle_to_redis('chat_mems', chat_mems) embed = discord.Embed(description="<:ivareset:1051691297443950612>", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=False) @tree.command(name = "help", description="get started") async def help(interaction): mention = interaction.user.mention embed = discord.Embed(title=f"Welcome. Let's **Get Started**.\n\n", color=discord.Color.dark_theme()) embed.set_thumbnail(url=client.user.avatar.url) embed.add_field(name="Step One", value="Iva uses **[OpenAI](https://beta.openai.com)** to generate responses. Create an account with them to start.") embed.add_field(name="Step Two", value="Visit your **[API Keys](https://beta.openai.com/account/api-keys)** page and click **`+ Create new secret key`**.") embed.add_field(name="Step Three", value=f"Copy and paste that secret key (`sk-...`) when you run `/setup` with {client.user.mention}") embed1 = discord.Embed(title="Step One", color=discord.Color.dark_theme()) embed2 = discord.Embed(title="Step Two", color=discord.Color.dark_theme()) embed3 = discord.Embed(title="Step Three", color=discord.Color.dark_theme()) embed1.set_image(url="https://media.discordapp.net/attachments/1053423931979218944/1055535479140929606/Screenshot_2022-12-21_233858.png?width=960&height=546") embed2.set_image(url="https://media.discordapp.net/attachments/1053423931979218944/1055535478817947668/Screenshot_2022-12-21_234629.png?width=960&height=606") embed3.set_image(url="https://media.discordapp.net/attachments/1053423931979218944/1055535478507585578/Screenshot_2022-12-21_234900.png") await interaction.response.send_message(embeds=[embed, embed1, embed2, embed3], ephemeral=True) @tree.command(name = "tutorial", description="how to talk with iva") async def tutorial(interaction): mention = interaction.user.mention embed_main = discord.Embed(title="Introduction to Iva", description="there are two *separate* ways to talk to iva, both with their own conversation history: `@iva` and `/iva`. let's go over their differences, in addition to a other helpful tools.", color=discord.Color.dark_theme()) embed_main.set_thumbnail(url=client.user.avatar.url) embed_chat = discord.Embed(title="`@iva`", description="provides **chat** and **conversation** oriented answers. has personality, asks questions back, is more creative.", color=discord.Color.dark_theme()) embed_ask = discord.Embed(title="`/iva`", description="provides **academic** and **work** oriented answers. has less personality, is more focused on consistency and reliability.", color=discord.Color.dark_theme()) #embed_ask.add_field(inline=True, name="<:ivacontinue1:1051714712242491392> `Continue`", value="say more, extend the last prompt's response") #embed_ask.add_field(inline=True, name="<:ivaregenerate:1051697145713000580> `Regenerate`", value="replace the last prompt's response with a different one") embed_ask.add_field(inline=True, name="<:ivadelete:1095559772754952232> `Delete`", value="delete the last interaction with iva in the conversation.") embed_ask.add_field(inline=True, name="<:ivareset:1051691297443950612> `Reset`", value="reset conversation history, clear iva's memory with you in the channel.") embed_other = discord.Embed(title="Other", color=discord.Color.dark_theme()) embed_other.add_field(inline=True, name="`/reset`", value="reset `@iva` and `/iva` conversation history.") embed_other.add_field(inline=True, name="`/model`", value="switch between `gpt-4` and `gpt-3.5` models.") embed_other.add_field(inline=True, name="`/temperature`", value="change the temperature.") embed_other.add_field(inline=True, name="`/help`", value="show instructions for setup.") embed_other.add_field(inline=True, name="`/setup`", value="enter your key. `/help` for more info.") await interaction.response.send_message(embeds=[embed_main, embed_chat, embed_ask, embed_other], ephemeral=True) @tree.command(name = "features", description="learn all the features iva has to offer") async def tutorial(interaction): features_string = FEATURES features_intro = discord.Embed(title="Features", description="Becoming familiar with all Iva has to offer will allow you to maximize your workflow. This list is constantly being updated, so be on the look out!", color=discord.Color.dark_theme()) features_intro.set_thumbnail(url=client.user.avatar.url) feature_list = discord.Embed(description=textwrap.dedent(features_string).strip(), color=discord.Color.dark_theme()) embeds = [ features_intro, feature_list, ] await interaction.response.send_message(embeds=embeds, ephemeral=True) @tree.command(name = "setup", description="register your key") @app_commands.describe(key = "key") async def setup(interaction, key: str = None): id = interaction.user.id mention = interaction.user.mention if key is None: await delete_key(id) embed = discord.Embed(description=f"<:ivathumbsup:1051918474299056189> **Key deleted for {mention}.**", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return # Use the `SELECT` statement to fetch the row with the given id result = await fetch_key(id) if result != None: # Access the values of the columns in the row if key != result[0]: await upsert_key(str(id), key) embed = discord.Embed(description=f"<:ivathumbsup:1051918474299056189> **Key updated for {mention}.**", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return elif key == result[0]: embed = discord.Embed(description=f"<:ivaerror:1051918443840020531> **Key already registered for {mention}.**", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=10) return else: view = Opt(key=key) embed = discord.Embed(description=f"<:ivanotify:1051918381844025434> **{mention} In order to use Iva, you must agree to our [Privacy Policy](https://iva.gg/privacy) and [Terms of Service](https://iva.gg/terms)**.\n\nPlease take a few minutes to read and understand them both.", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, view=view) @tree.command(name = "model", description="choose a completion model") @app_commands.choices(choices=[ app_commands.Choice(name="gpt-3.5-turbo-4k ($0.002 / 1k tokens)", value="gpt-3.5-turbo"), app_commands.Choice(name="gpt-3.5-turbo-16k ($0.004 / 1k tokens)", value="gpt-3.5-turbo-16k"), app_commands.Choice(name="gpt-4-8k ($0.06 / 1k tokens)", value="gpt-4"), ]) async def model(interaction, choices: app_commands.Choice[str] = None): id = interaction.user.id mention = interaction.user.mention user_settings = await load_pickle_from_redis('user_settings') if choices is not None: user_settings.setdefault(id, {})['model'] = choices.value await save_pickle_to_redis('user_settings', user_settings) embed = discord.Embed(description=f"<:ivamodel:1096498759040520223> **set model to `{choices.value}` for {mention}.**", color=discord.Color.dark_theme()) else: try: current_model = user_settings.get(id)["model"] except KeyError: current_model = "gpt-3.5-turbo" except TypeError: current_model = "gpt-3.5-turbo" embed = discord.Embed(description=f"<:ivamodel:1096498759040520223> **Current Model:** `{current_model}`", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=30) return @tree.command(name = "temperature", description="set a default temperature to use with iva.") @app_commands.describe(temperature = "temperature") async def temperature(interaction, temperature: float = None): id = interaction.user.id mention = interaction.user.mention user_settings = await load_pickle_from_redis('user_settings') if temperature is not None: if not (temperature >= 0.0 and temperature <= 2.0): embed = discord.Embed(description=f"<:ivaerror:1051918443840020531> **{mention} `temperature` must be a float value from 0.0-2.0.**", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=30) return user_settings.setdefault(id, {})['temperature'] = temperature await save_pickle_to_redis('user_settings', user_settings) embed = discord.Embed(description=f"<:ivatemp:1097754157747818546>**set temperature to `{temperature}` for {mention}.**", color=discord.Color.dark_theme()) else: try: temperature = user_settings.get(id)["temperature"] except KeyError: temperature = "0.5" except TypeError: temperature = "0.5" embed = discord.Embed(description=f"<:ivatemp:1097754157747818546>**Current Temperature:** `{temperature}`", color=discord.Color.dark_theme()) await interaction.response.send_message(embed=embed, ephemeral=True, delete_after=30) return client.run(DISCORD_TOKEN)
[ "\"{text}\"", "chat_history", "agent_scratchpad", "<@1050437164367880202>", "[PLACEHOLDER, PLACEHOLDER]", "PLACEHOLDER→ PLACEHOLDERPLACEHOLDER\n\n`PLACEHOLDER` `PLACEHOLDER` `PLACEHOLDER` `PLACEHOLDER`", "input" ]
2024-01-10
anhornsby/coherent-representations
simulation~simulate.py
# -*- coding: utf-8 -*- # !/usr/bin/env python # Adam Hornsby """ Perform a simulation in which the Coherency Maximizing agent chooses between two choice types (1 and 2). These two choose types should be distinct on one attribute but the same on another. """ SEED = 30 import random import numpy as np from sklearn.datasets.samples_generator import make_blobs # own libraries from model import CoherencyMaximisingAgent from plot import plot_simulation_history np.random.seed(SEED) random.seed(SEED) # main configuration for the simulation CONFIG = { # initialise model 'preference': [0.5, 0.5], # initialised values of the preferences 'weights': [0.5, 0.5], # initialised values of the attention weights 'lr': 0.01, # the learning rate 'c': 1, # lambda value (i.e., "fussiness" parameter) 'epsilon_greedy': True, # use epsilon greedy selection or softmax selection? # simulation 'cluster_centers': [[0.2, 0.2], [0.2, 0.8]], 'n_choices': 500, 'cluster_std': 0.05, # std of the clusters 'n_timesteps': 10000, # outputs 'save_path': './figures/', } def simulate_blobs(centers, n_samples=500, cluster_std=1.5, random_state=32): """ Simulate 2 choice types as clusters within a 2-dimensional space # Parameters n_samples (int): Number of options to sample cluster_std (float): Standard deviation of clusters random_state (int): Random state by which to sample options """ X, y = make_blobs(n_samples=n_samples, centers=centers, cluster_std=cluster_std, random_state=random_state) # clip values to be within the space (between 0 and 1) X = np.clip(X, 0, 1) return X, y def update_agent(mod, action, observation): """ Determine gradient of choice # Parameters mod (CoherencyMaximisingAgent): Model agent object action (int): Either 1 or 0 depending on choice type made observation (numpy.ndarray): Two dimensional matrix describing the attributes of the two choices """ mod.update_agent(observation, action) # extract the current preference and attention weights, for plotting pref = mod.h0.preference_ attention = mod.h0.attention_weights_ return pref, attention def create_random_observation(choice_ones, choice_twos, n): """ Randomly select n of choice_ones and n of choice_twos and then row concatenate """ choice_one = choice_ones[np.random.choice(choice_ones.shape[0], n), :] choice_two = choice_twos[np.random.choice(choice_twos.shape[0], n), :] return np.vstack([choice_one, choice_two]) def simulate_choices(X, y, model, n_choices, epsilon=0.05, epsilon_greedy=True): """ Simulate the model for n_choices, taking an softmax exploration strategy # Parameters X (numpy.ndarray): Numpy multidimensional containing all possible observations y (numpy.ndarray): Vector describing the choice type (1 or 2) of observations model (CoherencyMaximisingAgent): Model agent n_choices (int): Number of choices by which to simulate epsilon (float): Probability of taking an exploratory action, if epsilon_greedy=True epsilon_greedy (bool): Whether to use epsilon greedy exploration or softmax exploration """ pref_hist = list() attention_hist = list() # now make n_choices according to a e-greedy strategy for _ in range(n_choices): # select a random two products from choice type 1 and 2 observation = create_random_observation(X[y == 0], X[y == 1], 1) observation = observation.T # transpose for model compatability # determine the probability of making choice 1 or 2 probs = model.feed_forward(observation) if epsilon_greedy: # use epsilon greedy exploration rnd = np.random.rand() if rnd < epsilon: action = np.random.choice([0, 1]) else: action = np.argmax(probs) else: # use softmax exploration action = np.random.choice([0, 1], p=probs) # update the agent given the choice pref, attention = update_agent(model, action, observation) # update preference history pref_hist.append(pref) attention_hist.append(attention) return np.vstack(pref_hist), np.vstack(attention_hist) def main(config): """Main entrypoint for the simulation code""" # simulate three clusters X, y = simulate_blobs(config['cluster_centers'], n_samples=config['n_choices'], cluster_std=config['cluster_std']) # initialise the agent mod = CoherencyMaximisingAgent(2, 2, learn_prefs=True, learn_weights=True, c=config['c'], p_eta=config['lr'], w_eta=config['lr'], p_init=config['preference'], w_init=config['weights']) # simulate choices for n_timesteps pref_hist, att_hist = simulate_choices(X, y, mod, n_choices=config['n_timesteps'], epsilon_greedy=config['epsilon_greedy']) # plot the simulation history in a 2d plot. save to file. plot_simulation_history(X, y, pref_hist, att_hist, save_path=config['save_path'] + '2d_axis_plot.eps')
[]
2024-01-10
aubustou/range_bd
range_bd~get_file_names.py
from pathlib import Path import openai openai.api_key = "EMPTY" # Not support yet openai.api_base = "" model = "vicuna-7b-v1.3" prompt = """I need to clean up filenames. Those are comic books. I need a format with <series> #tome_number.zip Comanche-Greg-Hermann-Integrale-NB-T01.zip Astérix n°03 - Astérix et les Goths.zip (2021) Elzear (tome 1) - Le dejeuner - Maco [cbz].cbz Format into JSON. """ def main(): # create a chat completion completion = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": prompt}] ) # print the completion print(completion.choices[0].message.content) BD_PATH = Path("M:\Bédés") for path in BD_PATH.rglob("*.zip"): print(str(path).removeprefix(f"{BD_PATH}\\"))
[ "I need to clean up filenames. Those are comic books. I need a format with <series> #tome_number.zip\nComanche-Greg-Hermann-Integrale-NB-T01.zip\nAstérix n°03 - Astérix et les Goths.zip\n(2021) Elzear (tome 1) - Le dejeuner - Maco [cbz].cbz\nFormat into JSON.\n" ]
2024-01-10
metagov/d20-governance
d20_governance~utils~cultures.py
import random import asyncio import datetime import discord from discord import app_commands from d20_governance.utils.constants import GOVERNANCE_SVG_ICONS from langchain.prompts import PromptTemplate from langchain.llms import OpenAI from langchain.chains import LLMChain from langchain.chat_models import ChatOpenAI from abc import ABC, abstractmethod from collections import defaultdict from colorama import Fore, Style # This is a custom set that tracks order or append and removal as well as groups of channels through sets class OrderedSet: def __init__(self): self.set = set() self.list = [] def add(self, item): if item not in self.set: self.set.add(item) self.list.append(item) def remove(self, item): if item in self.set: self.set.discard(item) self.list.remove(item) def __iter__(self): return iter(self.list) def __len__(self): return len( self.list ) # The length of the ListSet is the length of the internal list def __bool__(self): return len(self) > 0 # The instance is "Truthy" if there are elements in it class RandomCultureModuleManager: def __init__(self): self.random_culture_module = "" random_culture_module_manager = RandomCultureModuleManager() class ValueRevisionManager: def __init__(self): self.proposed_values_dict = {} self.agora_values_dict = { "Respect": "Our members should treat each other with respect, recognizing and appreciating diverse perspectives and opinions.", "Inclusivity": "Our community strives to be inclusive, creating an environment where everyone feels welcome and valued regardless of their background, identity, or beliefs.", "Support": "Our members support and help one another, whether it's providing guidance, advice, or emotional support.", "Collaboration": "Our community encourage collaboration, fostering an environment where members can work together and share knowledge or skills.", "Trust": "Our community believes building trust is important, as it allows members to feel safe and comfortable sharing their thoughts and experiences.", } self.selected_value = {} self.game_quest_values_dict = {} self.quest_game_channels = [] self.lock = asyncio.Lock() def get_value_choices(self): choices = [ app_commands.Choice(name=f"{name}: {value[:60]}", value=name) for name, value in value_revision_manager.agora_values_dict.items() ] return choices async def store_proposal( self, proposed_value_name_input, proposed_value_definition_input ): async with self.lock: proposed_value_name = proposed_value_name_input.value.strip() proposed_value_definition = proposed_value_definition_input.value.strip() self.proposed_values_dict[proposed_value_name] = proposed_value_definition async def update_values_dict(self, select_value, vote_result): async with self.lock: if not vote_result: print("value dict not updated") else: if select_value in value_revision_manager.agora_values_dict: del value_revision_manager.agora_values_dict[select_value] value_revision_manager.agora_values_dict.update(vote_result) message_content = "" for ( value, description, ) in value_revision_manager.agora_values_dict.items(): message_content += f"{value}:\n{description}\n\n" message = f"```{message_content}```" module = CULTURE_MODULES.get("values", None) module.config["values_list"] = message async def clear_proposed_values(self): async with self.lock: self.proposed_values_dict.clear() value_revision_manager = ValueRevisionManager() class PromptObject: def __init__(self): self.decision_one = "" self.decision_two = "" self.decision_three = "" prompt_object = PromptObject() class CultureModule(ABC): def __init__(self, config): self.config = config # This hold the configuration for the module if "guild_channel_map" not in self.config: self.config["guild_channel_map"] = {} # if "channels" not in self.config: # self.config["channels"] = set() async def filter_message( self, message: discord.Message, message_string: str ) -> str: return message_string # State management with channel and guild mapping async def toggle_local_state_per_channel(self, ctx, guild_id, channel_id): print("Toggling module...") if self.is_local_state_active_in_channel(guild_id, channel_id): await self.deactivate_local_state_in_channel(ctx, guild_id, channel_id) else: await self.activate_local_state_in_channel(ctx, guild_id, channel_id) async def toggle_local_state_per_channel(self, ctx, guild_id, channel_id): print("Toggling module...") if self.is_local_state_active_in_channel(guild_id, channel_id): await self.deactivate_local_state_in_channel(ctx, guild_id, channel_id) else: await self.activate_local_state_in_channel(ctx, guild_id, channel_id) def is_local_state_active_in_channel(self, guild_id, channel_id): print("Returning local state of active modules...") return ( guild_id in self.config["guild_channel_map"] and channel_id in self.config["guild_channel_map"][guild_id] ) async def activate_local_state_in_channel(self, ctx, guild_id, channel_id): print("Activating module...") if guild_id not in self.config["guild_channel_map"]: self.config["guild_channel_map"][guild_id] = set() self.config["guild_channel_map"][guild_id].add(channel_id) await toggle_culture_module(guild_id, channel_id, self.config["name"], True) await display_culture_module_state( ctx, guild_id, channel_id, self.config["name"], True ) async def deactivate_local_state_in_channel(self, ctx, guild_id, channel_id): print("Deactivating module...") channels_for_guild = self.config["guild_channel_map"].get(guild_id, None) if channels_for_guild and channel_id in channels_for_guild: self.config["guild_channel_map"][guild_id].discard(channel_id) await toggle_culture_module( guild_id, channel_id, self.config["name"], False ) await display_culture_module_state( ctx, guild_id, channel_id, self.config["name"], False ) # Timeout method async def timeout(self, ctx, guild_id, channel_id, timeout): print("Starting Timeout Task") await asyncio.sleep(timeout) print("ending Timeout Task") if ( not self.is_local_state_active() ): # Check is module is still deactivated locally after waiting # if not self.activate_global_state(ctx, guild_id, channel_id) class Obscurity(CultureModule): # Message string may be pre-filtered by other modules async def filter_message( self, message: discord.Message, message_string: str ) -> str: print(f"{Fore.GREEN}※ applying obscurity module{Style.RESET_ALL}") # Get the method from the module based on the value of "mode" method = getattr(self, self.config["mode"]) # Call the method filtered_message = method(message_string) return filtered_message def scramble(self, message_string): words = message_string.split() scrambled_words = [] for word in words: if len(word) <= 3: scrambled_words.append(word) else: middle = list(word[1:-1]) random.shuffle(middle) scrambled_words.append(word[0] + "".join(middle) + word[-1]) return " ".join(scrambled_words) def replace_vowels(self, message_string): vowels = "aeiou" message_content = message_string.lower() return "".join([" " if c in vowels else c for c in message_content]) def pig_latin(self, message_string): words = message_string.split() pig_latin_words = [] for word in words: if word[0] in "aeiouAEIOU": pig_latin_words.append(word + "yay") else: first_consonant_cluster = "" rest_of_word = word for letter in word: if letter not in "aeiouAEIOU": first_consonant_cluster += letter rest_of_word = rest_of_word[1:] else: break pig_latin_words.append(rest_of_word + first_consonant_cluster + "ay") return " ".join(pig_latin_words) def camel_case(self, message_string): words = message_string.split() camel_case_words = [word.capitalize() for word in words] return "".join(camel_case_words) class Wildcard(CultureModule): async def filter_message( self, message: discord.Message, message_string: str ) -> str: """ A LLM filter for messages made by users """ print(f"{Fore.GREEN}※ applying wildcard module{Style.RESET_ALL}") module = CULTURE_MODULES.get("wildcard", None) llm = ChatOpenAI(temperature=0.1, model_name="gpt-3.5-turbo") prompt = PromptTemplate( input_variables=[ "input_text", "group_name", "group_topic", "group_way_of_speaking", ], template="You are from {group_name}. Please rewrite the following input ina way that makes the speaker sound {group_way_of_speaking} while maintaining the original meaning and intent. Incorporate the theme of {group_topic}. Don't complete any sentences, just rewrite them. Input: {input_text}", ) chain = LLMChain(llm=llm, prompt=prompt) response = await chain.arun( { "group_name": prompt_object.decision_one, "group_topic": prompt_object.decision_two, "group_way_of_speaking": prompt_object.decision_three, "input_text": message_string, } ) return response class Amplify(CultureModule): async def filter_message( self, message: discord.Message, message_string: str ) -> str: """ A LLM filter for messages during the /eloquence command/function """ print(f"{Fore.GREEN}※ applying amplify module{Style.RESET_ALL}") llm = ChatOpenAI(temperature=0.1, model_name="gpt-3.5-turbo") prompt = PromptTemplate( input_variables=["input_text"], template="Using the provided input text, generate a revised version that amplifies its sentiment to a much greater degree. Maintain the overall context and meaning of the message while significantly heightening the emotional tone. You must ONLY respond with the revised message. Input text: {input_text}", ) chain = LLMChain(llm=llm, prompt=prompt) response = await chain.arun(message_string) return response class Ritual(CultureModule): async def filter_message( self, message: discord.Message, message_string: str ) -> str: print(f"{Fore.GREEN}※ applying ritual module{Style.RESET_ALL}") async for msg in message.channel.history(limit=100): if msg.id == message.id: continue if msg.author.bot and not msg.content.startswith( "※" ): # This condition lets webhook messages to be checked continue if msg.content.startswith("/") or msg.content.startswith("-"): continue previous_message = msg.content break if previous_message is None: return message_string filtered_message = await self.initialize_ritual_agreement( previous_message, message_string ) return filtered_message async def initialize_ritual_agreement(self, previous_message, new_message): llm = ChatOpenAI(temperature=0.9) prompt = PromptTemplate( input_variables=["previous_message", "new_message"], template="Write a message that reflects the content in the message '{new_message}' but is cast in agreement with the message '{previous_message}'. Preserve and transfer the meaning and any spelling errors or text transformations in the message in the response.", ) # FIXME: This template does not preserve obscurity text processing. Maybe obscurity should be reaplied after ritual if active in the active_culture_mode list chain = LLMChain(llm=llm, prompt=prompt) response = await chain.arun( previous_message=previous_message, new_message=new_message ) return response class Values(CultureModule): async def check_values(self, bot, ctx, message: discord.Message): print("Checking values") if message.reference: reference_message = await message.channel.fetch_message( message.reference.message_id ) if ( reference_message.author.bot and not reference_message.content.startswith( "※" ) # This condition lets webhook messages to be checked ): await ctx.send("Cannot check values of messages from bot") return else: print( f"Original Message Content: {reference_message.content}, posted by {message.author}" ) current_values_dict = value_revision_manager.agora_values_dict values_list = f"Community Defined Values:\n\n" for value in current_values_dict.keys(): values_list += f"* {value}\n" llm_response, alignment = await self.llm_analyze_values( current_values_dict, reference_message.content ) message_content = f"----------```Message: {reference_message.content}\n\nMessage author: {reference_message.author}```\n> **Values Analysis:** {llm_response}\n```{values_list}```\n----------" # Assign alignment roles to users if their post is values-checked if alignment == "aligned": await assign_role_to_user(message.author, "Aligned") else: await assign_role_to_user(message.author, "Misaligned") await ctx.send(message_content) else: if message.author.bot and not message.content.startswith("※"): await ctx.send("Cannot check values of messages from bot") return else: print( f"Original Message Contnet: {message.content}, posted by {message.author}" ) current_values_dict = value_revision_manager.agora_values_dict values_list = f"Community Defined Values:\n\n" for value in current_values_dict.keys(): values_list += f"* {value}\n" llm_response, alignment = await self.llm_analyze_values( current_values_dict, message.content ) message_content = f"----------```Message: {message.content}\n\nMessage author: {message.author}```\n> **Values Analysis:** {llm_response}\n```{values_list}```\n----------" # Assign alignment roles to users if their post is values-checked if alignment == "aligned": await assign_role_to_user(message.author, "Aligned") else: await assign_role_to_user(message.author, "Misaligned") await ctx.send(message_content) async def llm_analyze_values(self, values_dict, text): """ Analyze message content based on values """ print(f"{Fore.GREEN}※ applying values module{Style.RESET_ALL}") llm = ChatOpenAI(temperature=0.5, model_name="gpt-3.5-turbo") template = f"We hold and maintain a set of mutually agreed-upon values. Analyze whether the message '{text}' is in accordance with the values we hold:\n\n" current_values_dict = value_revision_manager.agora_values_dict for ( value, description, ) in values_dict.items(): template += f"- {value}: {description}\n" template += f"\nNow, analyze the message:\n{text}. Start the message with either the string 'This message aligns with our values' or 'This message does not align with our values'. Then briefly explain why the values are aligned or misaligned based on the values the group holds. Use no more than 250 characters." prompt = PromptTemplate.from_template(template=template) chain = LLMChain(llm=llm, prompt=prompt) response = await chain.arun({"text": text}) alignment = ( "aligned" if "This message aligns with our values" in response else "misaligned" ) return response, alignment # TODO: Finish implementing and refine # async def randomly_check_values(self, bot, ctx, channel): # while True: # print("in a value check loop") # current_time = datetime.datetime.utcnow() # print(f"time is: {current_time}") # # Randomly generate delay between executions # delay = random.randint(45, 55) # # Wait for the specified delay # await asyncio.sleep(delay) # try: # # Fetch a random message from a game channel # messages = [] # async for message in channel.history(limit=100, after=current_time): # if ( # message.content.startswith("※") # or isinstance(message, discord.Message) # and not message.author.bot # ): # messages.append(message) # if not messages: # print("No valid messages found in the channel") # return # # Generate a list of valid message IDs # valid_message_ids = [message.id for message in messages] # random_message_id = random.choice(valid_message_ids) # random_message = await channel.fetch_message(random_message_id) # print("fetched random message") # # Check values of the random message # await self.check_values(bot, channel, random_message) # except Exception as e: # print(f"Error occurred while checking values: {e}") # except discord.NotFound: # print("Random message not found") # except discord.HTTPException as e: # print(f"Error occurrent while fetching random message: {e}") async def assign_role_to_user(user, role_name): guild = user.guild new_role = discord.utils.get(guild.roles, name=role_name) # Define role variables aligned_role = discord.utils.get(guild.roles, name="Aligned") misaligned_role = discord.utils.get(guild.roles, name="Misaligned") # Check if the user already has an alignment role if aligned_role in user.roles and new_role == misaligned_role: await user.remove_roles(aligned_role) elif misaligned_role in user.roles and new_role == aligned_role: await user.remove_roles(misaligned_role) await user.add_roles(new_role) class Eloquence(CultureModule): async def filter_message( self, message: discord.Message, message_string: str ) -> str: """ A LLM filter for messages during the /eloquence command/function """ print(f"{Fore.GREEN}※ applying eloquence module{Style.RESET_ALL}") llm = ChatOpenAI(temperature=0.5, model_name="gpt-3.5-turbo") prompt = PromptTemplate.from_template( template="You are from the Shakespearean era. Please rewrite the following input in a way that makes the speaker sound as eloquent, persuasive, and rhetorical as possible, while maintaining the original meaning and intent. Don't complete any sentences, jFust rewrite them. Input: {input_text}" ) prompt.format( input_text=message_string ) # TODO: is both formatting and passing the message_string necessary? chain = LLMChain(llm=llm, prompt=prompt) response = await chain.arun(message_string) return response ACTIVE_MODULES_BY_CHANNEL = defaultdict(OrderedSet) async def toggle_culture_module(guild_id, channel_id, module_name, state): """ If state is True, turn on the culture module if state is False, turn off the culture module """ key = (guild_id, channel_id) active_modules_by_channel = ACTIVE_MODULES_BY_CHANNEL[key] if state: active_modules_by_channel.add(module_name) else: active_modules_by_channel.remove(module_name) # TODO: what does the variable "state" mean? async def display_culture_module_state(ctx, guild_id, channel_id, module_name, state): """ Send an embed displaying state of active culture moduled by channel """ print("Displaying culture module state...") key = (guild_id, channel_id) active_modules_by_channel = ACTIVE_MODULES_BY_CHANNEL[key] module = CULTURE_MODULES[module_name] # TODO: make state a more descriptive variable name if state: name = "Activated" value = module.config["activated_message"] else: name = "Deactivated" value = module.config["deactivated_message"] if active_modules_by_channel.list: active_culture_module_values = ", ".join(active_modules_by_channel.list) else: active_culture_module_values = "none" embed = discord.Embed( title=f"Culture: {module_name.upper()}", color=discord.Color.dark_gold() ) embed.set_thumbnail(url=module.config["url"]) embed.add_field( name=name, value=value, inline=False, ) if module.config["mode"] is not None and state: embed.add_field( name="Mode:", value=module.config["mode"], inline=False, ) if module.config["message_alter_mode"] == "llm" and state: embed.add_field( name="LLM Prompt:", value=module.config["llm_disclosure"], inline=False, ) if module.config["help"] and state: embed.add_field( name="How to use:", value=module.config["how_to_use"], inline=False, ) embed.add_field( name="Active Culture Modules:", value=active_culture_module_values, inline=False, ) if module.config["values_list"] is not None and state: embed.add_field( name="List of Current Community Values:", value=module.config["values_list"], inline=False, ) await ctx.send(embed=embed) def get_values_message(): message_content = "" for ( value, description, ) in value_revision_manager.agora_values_dict.items(): message_content += f"{value}:\n{description}\n\n" message = f"```{message_content}```" return message values_list = get_values_message() CULTURE_MODULES = { "wildcard": Wildcard( { "name": "wildcard", "global_state": False, "local_state": False, "mode": None, "help": False, "message_alter_mode": "llm", "llm_disclosure": None, "activated_message": "Messages will now be process through an LLM.", "deactivated_message": "Messages will no longer be processed through an LLM.", "url": "", # TODO: Add Wildcard URL "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": None, } ), "obscurity": Obscurity( { "name": "obscurity", "global_state": False, "local_state": False, "mode": "scramble", "help": False, "message_alter_mode": "text", "alter_message": True, "activated_message": "Messages will be distored based on mode of obscurity.", "deactivated_message": "Messages will no longer be distored by obscurity.", "url": "https://raw.githubusercontent.com/metagov/d20-governance/main/assets/imgs/embed_thumbnails/obscurity.png", "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": None, } ), "eloquence": Eloquence( { "name": "eloquence", "global_state": False, "local_state": False, "mode": None, "help": False, "message_alter_mode": "llm", "llm_disclosure": "You are from the Shakespearean era. Please rewrite the messages in a way that makes the speaker sound as eloquent, persuasive, and rhetorical as possible, while maintaining the original meaning and intent.", "activated_message": "Messages will now be process through an LLM.", "deactivated_message": "Messages will no longer be processed through an LLM.", "url": "https://raw.githubusercontent.com/metagov/d20-governance/main/assets/imgs/embed_thumbnails/eloquence.png", "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": None, } ), "ritual": Ritual( { "name": "ritual", "global_state": False, "local_state": False, "mode": None, "help": False, "message_alter_mode": "llm", "llm_disclosure": "Write a message that reflects the content in the posted message and is cast in agreement with the previous message. Preserve and transfer any spelling errors or text transformations in these messages in the response.", "activated_message": "A ritual of agreement permeates throughout the group.", "deactivated_message": "Automatic agreement has ended. But will the effects linger in practice?", "url": "", # TODO: make ritual img "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": None, } ), "amplify": Amplify( { "name": "amplify", "global_state": False, "local_state": False, "mode": None, "help": False, "message_alter_mode": "llm", "llm_disclosure": "Using the provided input text, generate a revised version that amplifies its sentiment to a much greater degree. Maintain the overall context and meaning of the message while significantly heightening the emotional tone.", "activated_message": "Sentiment amplification abounds.", "deactivated_message": "Sentiment amplification has ceased.", "url": "", # TODO: make amplify img "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": None, } ), "values": Values( { "name": "values", "global_state": False, "mode": None, "help": True, "how_to_use": "Your posts are now subject to alignment analysis. The content of posts will be randomly analyized to see how aligned they are with the group's values. You can also reply to the message you want to check and type `check-values`. you will be labled either aligned or misaligned based on analysis.", "local_state": False, "message_alter_mode": None, "llm_disclosure": "You hold and maintain a set of mutually agreed upon values. The values you maintain are the values defined by the community. You review the contents of messages sent for validation and analyze the contents in terms of the values you hold. You describe in what ways the input text are aligned or unaligned with the values you hold.", "activated_message": "A means of validating the cultural alignment of this online communiuty is nafculture_moduow available. Respond to a message with check-values.", "deactivated_message": "Automatic measurement of values is no longer present, through an essence of the culture remains, and you can respond to messages with `check-values` to check value alignment.", "url": "", # TODO: make values img "icon": GOVERNANCE_SVG_ICONS["culture"], "input_value": 0, "values_list": values_list, } ), } async def send_msg_to_random_player(game_channel): print("Sending random DM...") players = [member for member in game_channel.members if not member.bot] random_player = random.choice(players) dm_channel = await random_player.create_dm() await dm_channel.send( "🌟 Greetings, esteemed adventurer! A mischievous gnome has entrusted me with a cryptic message just for you: 'In the land of swirling colors, where unicorns prance and dragons snooze, a hidden treasure awaits those who dare to yawn beneath the crescent moon.' Keep this message close to your heart and let it guide you on your journey through the wondrous realms of the unknown. Farewell, and may your path be ever sprinkled with stardust! ✨" )
[ "input_text", "You are from the Shakespearean era. Please rewrite the following input in a way that makes the speaker sound as eloquent, persuasive, and rhetorical as possible, while maintaining the original meaning and intent. Don't complete any sentences, jFust rewrite them. Input: {input_text}", "new_message", "Using the provided input text, generate a revised version that amplifies its sentiment to a much greater degree. Maintain the overall context and meaning of the message while significantly heightening the emotional tone. You must ONLY respond with the revised message. Input text: {input_text}", "group_topic", "You are from {group_name}. Please rewrite the following input ina way that makes the speaker sound {group_way_of_speaking} while maintaining the original meaning and intent. Incorporate the theme of {group_topic}. Don't complete any sentences, just rewrite them. Input: {input_text}", "group_way_of_speaking", "We hold and maintain a set of mutually agreed-upon values. Analyze whether the message 'PLACEHOLDER' is in accordance with the values we hold:\n\n", "Write a message that reflects the content in the message '{new_message}' but is cast in agreement with the message '{previous_message}'. Preserve and transfer the meaning and any spelling errors or text transformations in the message in the response.", "- PLACEHOLDER: PLACEHOLDER\n", "previous_message", "\nNow, analyze the message:\nPLACEHOLDER. Start the message with either the string 'This message aligns with our values' or 'This message does not align with our values'. Then briefly explain why the values are aligned or misaligned based on the values the group holds. Use no more than 250 characters.", "group_name" ]
2024-01-10
matttbates/job-search-assistant
crew.py
from langchain.llms import Ollama from crewai import Agent, Task, Crew, Process ollama_openhermes = Ollama(model="openhermes") from langchain.tools import DuckDuckGoSearchRun search_tool = DuckDuckGoSearchRun() researcher = Agent( role='Researcher', goal='Research Android Job openings', backstory='You are a job search assistant specialized in finding relevant job openings', verbose=True, allow_delegation=False, llm=ollama_openhermes, tools=[search_tool] ) writer = Agent( role='Writer', goal='Write compelling cover letters', backstory='You are a Job search assistant specialized in writing cover letters that land jobs.', verbose=True, allow_delegation=False, llm=ollama_openhermes ) task1 = Task( description='Investigate LinkedIn for the latest Android job offers around Calgary and Canadian remote positions.', agent=researcher ) task2 = Task( description='Write a compelling cover letter to land a job interview.', agent=writer ) crew = Crew( agents=[researcher, writer], tasks=[task1, task2], verbose=2, process=Process.sequential ) result = crew.kickoff()
[]
2024-01-10
eden-chan/devils-advocate
backend~temp.py
import os import openai from flask import Flask from flask_cors import CORS openai.api_key = "" def alice_function(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ # Set CORS headers for the preflight request if request.method == 'OPTIONS': # Allows GET requests from any origin with the Content-Type # header and caches preflight response for an 3600s headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': ['GET','POST'], 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } return ('', 204, headers) headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': ['GET', 'POST'], 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } # list engines if request.args and 'engine' in request.args: engines = openai.Engine.list() return engines, 200, headers # list files if request.args and 'file' in request.args: files = openai.File.list() return files, 200, headers # query answers engine if request.args and 'query' in request.args: # params model = 'ada' search_model = 'ada' temp = 0 max_rerank = 200 tokens = 1000 config = '1' # Args query = request.args.get('query') if request.args.get('model'): model = request.args.get('model') if request.args.get('search_model'): search_model = request.args.get('search_model') if request.args.get('max_rerank'): temp = request.args.get('temp') if request.args.get('max_rerank'): max_rerank = request.args.get('max_rerank') if request.args.get('tokens'): tokens = request.args.get('tokens') if request.args.get('config'): config = request.args.get('config') print(query, model, search_model, temp, max_rerank, tokens, config) # Configs if config == '1': # Financial reports file = "file-oQDJdeZM3XwDINp4Os7FKegb" context = "The ERG Group is a major independent operator in the production of electricity from renewable sources such as wind,\nsolar, hydroelectric and high-efficiency, low environmental impact cogenerative thermoelectric power plants.\nManagement of the industrial and commercial processes of the ERG Group is entrusted to the subsidiary ERG Power\nGeneration S.p.A. which carries out:\n• centralised Energy Management activities for all the generation technologies in which the ERG Group operates;\n• the Operation and Maintenance activities of its Italian wind farms and part of the plants in France and Germany, as\nwell as the Terni Hydroelectric Complex and the Priolo CCGT plant. It provides technical and administrative services\nin France and Germany for both Group companies and third parties through its foreign subsidiaries." examples = [["EBTDA third quarter 2019?", "99 million"], ["What is the business of ERG?", "The ERG Group is a major independent operator in the production of electricity from renewable sources such as wind, solar, hydroelectric and high-efficiency, low environmental impact cogenerative thermoelectric power plants"], ["What was the devation of the revenue between 2018-2019?", "From 2018 and 2019 the revenue is decreased of 0,496%, passing from 1,026.7 milions to 1,021.6 (adjusted)"]] if config == '2': # Artificial intelligence file = "file-jHcx2gRg1kIp2CKj0rsba84o" context_1 = "Number of AI journal publications grew by 34.5% from 2019 to 2020" context_2 = "" context_3 = "" example_1 = ["Growth of published AI journals 2018 to 2020?", "19.6% 2018 - 2019 and increased to 34.5% from 2019 to 2020"] example_2 = ["", ""] example_3 = ["", ""] context = context_1 + " " + context_2 + " " + context_3 examples = [example_1] if config == '3': # something else file = "file-WxyUG1r8XHtboyUAODO85dam" context = "The ERG Group is a major independent operator in the production of electricity from renewable sources such as wind,\nsolar, hydroelectric and high-efficiency, low environmental impact cogenerative thermoelectric power plants.\nManagement of the industrial and commercial processes of the ERG Group is entrusted to the subsidiary ERG Power\nGeneration S.p.A. which carries out:\n• centralised Energy Management activities for all the generation technologies in which the ERG Group operates;\n• the Operation and Maintenance activities of its Italian wind farms and part of the plants in France and Germany, as\nwell as the Terni Hydroelectric Complex and the Priolo CCGT plant. It provides technical and administrative services\nin France and Germany for both Group companies and third parties through its foreign subsidiaries." examples = [["Which is the EBTDA in the third quarter of 2019?", "99 million"],["What is the business of ERG?", "The ERG Group is a major independent operator in the production of electricity from renewable sources such as wind, solar, hydroelectric and high-efficiency, low environmental impact cogenerative thermoelectric power plants"], ["What was the devation of the revenue between 2018-2019?", "From 2018 and 2019 the revenue is decreased of 0,496%, passing from 1,026.7 milions to 1,021.6 (adjusted)"]] # models ada, babbage, curie, and davinci alice = openai.Answer.create( search_model=search_model, model=model, temperature=float(temp), return_metadata=True, return_prompt=True, max_rerank=int(max_rerank), n=1, question=query, file=file, examples_context=context, examples=examples, max_tokens=int(tokens), stop=["\n", "<|endoftext|>"], ) responsdata = alice print(responsdata) return responsdata, 200, headers else: return 'error', 400, headers
[]
2024-01-10
eden-chan/devils-advocate
backend~tests.py
import os import openai from openai.error import InvalidRequestError from fastapi import Depends, BackgroundTasks, status from fastapi.responses import JSONResponse openai.api_key = "" # response = openai.Answer.create( # search_model="curie", # model="davinci", # question="africA?", # file="file-2FLzlUNzq2KcFl6gnS0MSbN5", # examples_context="In 2017, U.S. life expectancy was 78 years.", # examples=[["What is human life expectancy in the United States?","78 years."]], # max_tokens=1500, # temperature=1, # stop=["\n", "<|endoftext|>"], # ) # # print(response) def answers(): try: response = openai.Answer.create( search_model="curie", model="davinci", question="africA?", file="file-2FLzlUNzq2KcFl6gnS0MSbN5", examples_context="In 2017, U.S. life expectancy was 78 years.", examples=[["What is human life expectancy in the United States?", "78 years."]], max_tokens=1500, temperature=1, stop=["\n", "<|endoftext|>"], ) print(response) except InvalidRequestError: return JSONResponse({}, status_code=status.HTTP_204_NO_CONTENT) answers()
[]
2024-01-10
pixegami/basic-langchain-examples
1_basic_example.py
from langchain.prompts import PromptTemplate from langchain.chat_models.openai import ChatOpenAI llm = ChatOpenAI() # Basic Example of a Prompt. response = llm.predict("What are the 7 wonders of the world?") print(f"Response: {response}") # Basic Example of a Prompt Template. prompt_template = PromptTemplate.from_template( "List {n} cooking recipe ideas {cuisine} cuisine (name only)." ) prompt = prompt_template.format(n=3, cuisine="italian") print(f"Templated Prompt: {prompt}") response = llm.predict(prompt) print(f"Response: {response}")
[ "italian", "List {n} cooking recipe ideas {cuisine} cuisine (name only)." ]
2024-01-10
pixegami/basic-langchain-examples
4_agent_example.py
from langchain.utilities import SerpAPIWrapper from langchain.agents import Tool from langchain.chains import LLMMathChain from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.tools.render import format_tool_to_openai_function from langchain.chat_models.openai import ChatOpenAI from langchain.agents.format_scratchpad import format_to_openai_functions from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.agents import AgentExecutor llm = ChatOpenAI() llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True) # Set "SERPAPI_API_KEY" environment variable to your private key. # https://serpapi.com/ search = SerpAPIWrapper() tools = [ Tool( name="search", description="Search for information Google.", func=search.run, ), Tool( name="calculator", description="Use this tool to calculate the difference between numbers.", func=llm_math_chain.run, ), ] prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant"), ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad"), ] ) llm_with_tools = llm.bind(functions=[format_tool_to_openai_function(t) for t in tools]) agent_schema = { "input": lambda x: x["input"], "agent_scratchpad": lambda x: format_to_openai_functions(x["intermediate_steps"]), } agent = agent_schema | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser() agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) agent_executor.invoke({"input": "What is the population difference between 🇺🇸 and 🇬🇧?"})
[ "You are a helpful assistant", "agent_scratchpad", "{input}" ]
2024-01-10
pixegami/basic-langchain-examples
2_response_parser.py
from pydantic import BaseModel, Field from langchain.prompts import PromptTemplate from langchain.chat_models.openai import ChatOpenAI from langchain.output_parsers import PydanticOutputParser class Movie(BaseModel): title: str = Field(description="The title of the movie.") genre: list[str] = Field(description="The genre of the movie.") year: int = Field(description="The year the movie was released.") llm = ChatOpenAI() parser = PydanticOutputParser(pydantic_object=Movie) prompt_template_text = """ Response with a movie recommendation based on the query:\n {format_instructions}\n {query} """ format_instructions = parser.get_format_instructions() prompt_template = PromptTemplate( template=prompt_template_text, input_variables=["query"], partial_variables={"format_instructions": format_instructions}, ) prompt = prompt_template.format(query="A 90s movie with Nicolas Cage.") text_output = llm.predict(prompt) parsed_output = parser.parse(text_output) print(parsed_output) # Using LCEL chain = prompt_template | llm | parser response = chain.invoke({"query": "A 90s movie with Nicolas Cage."}) print(response)
[ "\nResponse with a movie recommendation based on the query:\n\n{format_instructions}\n\n{query}\n", "A 90s movie with Nicolas Cage.", "format_instructions" ]
2024-01-10
pixegami/basic-langchain-examples
3_chain_example.py
from langchain.chains import LLMChain, SequentialChain from langchain.prompts import PromptTemplate from langchain.chat_models.openai import ChatOpenAI prompt_1 = """ Come up with a short plot synopsis summary (2-3 lines) for a {genre} movie. """ prompt_2 = """ Suggest 5 movie title ideas for this movie: \n\n {synopsis} """ llm = ChatOpenAI() p1_template = PromptTemplate.from_template(prompt_1) chain_1 = LLMChain(llm=llm, prompt=p1_template, output_key="synopsis") p2_template = PromptTemplate.from_template(prompt_2) chain_2 = LLMChain(llm=llm, prompt=p2_template, output_key="titles") complex_chain = SequentialChain( chains=[chain_1, chain_2], input_variables=["genre"], output_variables=["synopsis", "titles"], verbose=True, ) output = complex_chain({"genre": "comedy"}) print(f"Output: {output}")
[ "\nCome up with a short plot synopsis summary (2-3 lines) for a {genre} movie.\n", "\nSuggest 5 movie title ideas for this movie: \n\n {synopsis}\n" ]
2024-01-10
msandbu/gptsecurity
langchain-basic.py
import os os.environ["OPENAI_API_KEY"] = "ENTER OPENAI API KEY HERE" os.environ["SERPAPI_API_KEY"] = "ENTER SERPAPI KEY HERE" from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI llm = OpenAI(temperature=1) tools = load_tools(["serpapi", "llm-math"], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("what should I do to become an expert on Large language models and GPT?")
[]
2024-01-10
Jtrue27/ADL2019-Homeworks
HW3~a2c~vec_env~shmem_vec_env.py
""" An interface for asynchronous vectorized environments. Modify from OpenAI Baseline Reference: https://raw.githubusercontent.com/openai/baselines/master/baselines/common/vec_env/shmem_vec_env.py """ import multiprocessing as mp import numpy as np from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars import ctypes from .util import dict_to_obs, obs_space_info, obs_to_dict _NP_TO_CT = {np.float32: ctypes.c_float, np.int32: ctypes.c_int32, np.int8: ctypes.c_int8, np.uint8: ctypes.c_char, np.bool: ctypes.c_bool} class ShmemVecEnv(VecEnv): """ Optimized version of SubprocVecEnv that uses shared variables to communicate observations. """ def __init__(self, env_fns, spaces=None, context='spawn'): """ If you don't specify observation_space, we'll have to create a dummy environment to get it. """ ctx = mp.get_context(context) if spaces: observation_space, action_space = spaces else: dummy = env_fns[0]() observation_space, action_space = dummy.observation_space, dummy.action_space dummy.close() del dummy VecEnv.__init__(self, len(env_fns), observation_space, action_space) self.obs_keys, self.obs_shapes, self.obs_dtypes = obs_space_info(observation_space) self.obs_bufs = [ {k: ctx.Array(_NP_TO_CT[self.obs_dtypes[k].type], int(np.prod(self.obs_shapes[k]))) for k in self.obs_keys} for _ in env_fns] self.parent_pipes = [] self.procs = [] with clear_mpi_env_vars(): for env_fn, obs_buf in zip(env_fns, self.obs_bufs): wrapped_fn = CloudpickleWrapper(env_fn) parent_pipe, child_pipe = ctx.Pipe() proc = ctx.Process(target=_subproc_worker, args=(child_pipe, parent_pipe, wrapped_fn, obs_buf, self.obs_shapes, self.obs_dtypes, self.obs_keys)) proc.daemon = True self.procs.append(proc) self.parent_pipes.append(parent_pipe) proc.start() child_pipe.close() self.waiting_step = False self.viewer = None def reset(self): if self.waiting_step: self.step_wait() for pipe in self.parent_pipes: pipe.send(('reset', None)) return self._decode_obses([pipe.recv() for pipe in self.parent_pipes]) def step_async(self, actions): assert len(actions) == len(self.parent_pipes) for pipe, act in zip(self.parent_pipes, actions): pipe.send(('step', act)) def step_wait(self): outs = [pipe.recv() for pipe in self.parent_pipes] obs, rews, dones, infos = zip(*outs) return self._decode_obses(obs), np.array(rews), np.array(dones), infos def close_extras(self): if self.waiting_step: self.step_wait() for pipe in self.parent_pipes: pipe.send(('close', None)) for pipe in self.parent_pipes: pipe.recv() pipe.close() for proc in self.procs: proc.join() def get_images(self, mode='human'): for pipe in self.parent_pipes: pipe.send(('render', None)) return [pipe.recv() for pipe in self.parent_pipes] def _decode_obses(self, obs): result = {} for k in self.obs_keys: bufs = [b[k] for b in self.obs_bufs] o = [np.frombuffer(b.get_obj(), dtype=self.obs_dtypes[k]).reshape(self.obs_shapes[k]) for b in bufs] result[k] = np.array(o) return dict_to_obs(result) def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys): """ Control a single environment instance using IPC and shared memory. """ def _write_obs(maybe_dict_obs): flatdict = obs_to_dict(maybe_dict_obs) for k in keys: dst = obs_bufs[k].get_obj() dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shapes[k]) # pylint: disable=W0212 np.copyto(dst_np, flatdict[k]) env = env_fn_wrapper.x() parent_pipe.close() try: while True: cmd, data = pipe.recv() if cmd == 'reset': pipe.send(_write_obs(env.reset())) elif cmd == 'step': obs, reward, done, info = env.step(data) if done: obs = env.reset() pipe.send((_write_obs(obs), reward, done, info)) elif cmd == 'render': pipe.send(env.render(mode='rgb_array')) elif cmd == 'close': pipe.send(None) break else: raise RuntimeError('Got unrecognized cmd %s' % cmd) except KeyboardInterrupt: print('ShmemVecEnv worker: got KeyboardInterrupt') finally: env.close()
[]
2024-01-10
TrentBrick/Upside-Down-Free-Energy
utils~buffer.py
# pylint: disable=no-member import numpy as np import torch import random import bisect def combined_shape(length, shape=None): # taken from openAI spinning up. if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape) class SortedBuffer: """ Buffer that efficiently remains sorted. """ def __init__(self, obs_dim, act_dim, size, use_td_lambda_buf=False ): self.obs_buf = None self.obs2_buf= None self.act_buf= None self.discounted_rew_to_go_buf= None self.cum_rew= None self.horizon= None self.rollout_length = None self.final_obs = None self.buffer_dict = dict(obs=self.obs_buf, obs2=self.obs2_buf, act=self.act_buf, discounted_rew_to_go=self.discounted_rew_to_go_buf, cum_rew=self.cum_rew, horizon=self.horizon, rollout_length=self.rollout_length, final_obs=self.final_obs) self.use_td_lambda_buf = use_td_lambda_buf if self.use_td_lambda_buf: self.rollout_end_ind_buf = None self.raw_rew_buf = None self.buffer_dict['rollout_end_ind'] = self.rollout_end_ind_buf self.buffer_dict['raw_rew'] = self.raw_rew_buf self.size, self.max_size = 0, size self.total_num_steps_added = 0 def add_rollouts(self, list_of_rollout_dicts): # sorted in ascending order. largest values at the back. for rollout in list_of_rollout_dicts: # dont bother adding rollouts that are worse than the worst in the buffer. # but still count them to the overall number of rollouts seen. len_rollout = len(rollout['terminal']) self.total_num_steps_added += len_rollout if self.size == self.max_size and rollout['cum_rew'][0] <= self.buffer_dict['cum_rew'][-1]: continue self.size = min(self.size+len_rollout, self.max_size) if self.buffer_dict['obs'] is not None: # find where everything from this rollout should be inserted into # each of the numpy buffers. Uses the cumulative/terminal rewards # minus so that highest values are at the front. sort_ind = np.searchsorted(-self.buffer_dict['cum_rew'], -rollout['cum_rew'][0] ) end_ind = len_rollout+sort_ind else: end_ind = len_rollout if self.use_td_lambda_buf: # will be appended and treated like everything else. end_ind = np.repeat(end_ind, len_rollout) rollout['rollout_end_ind'] = end_ind for key in self.buffer_dict.keys(): # NOTE: assumes that buffer and rollout use the same keys! # needed at init! if self.buffer_dict[key] is None: self.buffer_dict[key] = rollout[key] else: self.buffer_dict[key] = np.insert(self.buffer_dict[key], sort_ind, rollout[key], axis=0) if key == 'rollout_end_ind': self.buffer_dict[key][end_ind[0]:] = self.buffer_dict[key][end_ind[0]:]+len_rollout if self.size >= self.max_size: # buffer is full. Need to trim! # this will have a bias in that it will favour # the longer horizons at the end of the training data # but it shouldnt make a major diff. self.buffer_dict[key] = self.buffer_dict[key][:self.max_size] def retrieve_path(self, start_index): end_index = self.buffer_dict['rollout_end_ind'][start_index] if end_index<= start_index: print("for sorted buffer shouldnt have looping here!") # we have looping obs = np.concatenate( [self.buffer_dict['obs'][start_index:], self.buffer_dict['obs'][:end_index]], axis=0) rew = np.concatenate( [self.buffer_dict['raw_rew'][start_index:], self.buffer_dict['raw_rew'][:end_index]], axis=0) else: obs = self.buffer_dict['obs'][start_index:end_index] rew = self.buffer_dict['raw_rew'][start_index:end_index] return torch.as_tensor(obs, dtype=torch.float32), torch.as_tensor(rew, dtype=torch.float32) def get_desires(self, last_few = 75): """ This function calculates the new desired reward and new desired horizon based on the replay buffer. New desired horizon is calculted by the mean length of the best last X episodes. New desired reward is sampled from a uniform distribution given the mean and the std calculated from the last best X performances. where X is the hyperparameter last_few. """ # it is the first occurence of each cumulative ind. unique_cum_rews, unique_cum_inds = np.unique(-self.buffer_dict['cum_rew'], return_index=True) #unique returns a sorted dictionary need to reverse it. unique_cum_rews, unique_cum_inds = -unique_cum_rews[:last_few], unique_cum_inds[:last_few] #The exploratory desired horizon dh0 is set to the mean of the lengths of the selected episodes new_desired_horizon = round( self.buffer_dict['rollout_length'][unique_cum_inds].mean() ) # from these returns calc the mean and std mean_returns = np.mean(unique_cum_rews) std_returns = np.std(unique_cum_rews) new_desired_state = self.buffer_dict['final_obs'][unique_cum_inds].mean(axis=0) return mean_returns, std_returns, new_desired_horizon, new_desired_state def __getitem__(self, idx): # turn this into a random value! #rand_ind = np.random.randint(0,self.size) # up to current max size. return self.sample_batch(idxs=idx) def __len__(self): return self.size #self.num_batches_per_epoch def sample_batch(self, idxs=None, batch_size=256): if idxs is None: idxs = np.random.randint(0, self.size, size=batch_size) return {key:torch.as_tensor(arr[idxs],dtype=torch.float32) for key, arr in self.buffer_dict.items()} class RingBuffer: """ A simple FIFO experience replay buffer for DDPG agents. # Taken from OpenAI spinning up. """ def __init__(self, obs_dim, act_dim, size, use_td_lambda_buf=False): self.obs_buf = np.zeros(combined_shape(size, obs_dim), dtype=np.float32) self.obs2_buf = np.zeros(combined_shape(size, obs_dim), dtype=np.float32) if act_dim==1: self.act_buf = np.zeros(size, dtype=np.float32) else: self.act_buf = np.zeros(combined_shape(size, act_dim), dtype=np.float32) self.discounted_rew_to_go_buf = np.zeros(size, dtype=np.float32) self.cum_rew = np.zeros(size, dtype=np.float32) self.final_obs = np.zeros(combined_shape(size, obs_dim), dtype=np.float32) self.horizon_buf = np.zeros(size, dtype=np.float32) #self.terminal_buf = np.zeros(size, dtype=np.int8) self.buf_list = [self.obs_buf, self.obs2_buf, self.discounted_rew_to_go_buf, self.act_buf, self.cum_rew, self.horizon_buf, self.final_obs ] self.value_names = ['obs', 'obs2', 'discounted_rew_to_go', 'act', 'cum_rew', 'horizon', 'final_obs' ] self.use_td_lambda_buf = use_td_lambda_buf if self.use_td_lambda_buf: self.rollout_end_ind_buf = np.zeros(size, dtype=np.int32) self.raw_rew_buf = np.zeros(size, dtype=np.float32) self.buf_list.append(self.raw_rew_buf) self.value_names.append('raw_rew') self.ptr, self.size, self.max_size = 0, 0, size self.total_num_steps_added = 0 def retrieve_path(self, start_index): end_index = self.rollout_end_ind_buf[start_index] if end_index<= start_index: # we have looping obs = np.concatenate( [self.obs_buf[start_index:], self.obs_buf[:end_index]], axis=0) rew = np.concatenate( [self.raw_rew_buf[start_index:], self.raw_rew_buf[:end_index]], axis=0) else: obs = self.obs_buf[start_index:end_index] rew = self.raw_rew_buf[start_index:end_index] return torch.as_tensor(obs, dtype=torch.float32), torch.as_tensor(rew, dtype=torch.float32) def add_to_buffer(self,np_buf, iters_adding, data ): if (self.ptr+iters_adding)>self.max_size: amount_pre_loop = self.max_size-self.ptr amount_post_loop = iters_adding-amount_pre_loop np_buf[self.ptr:] = data[:amount_pre_loop] np_buf[:amount_post_loop] = data[amount_pre_loop:] else: np_buf[self.ptr:self.ptr+iters_adding] = data def add_rollouts(self, list_of_rollout_dicts): for rollout in list_of_rollout_dicts: iters_adding = len(rollout['terminal']) self.total_num_steps_added += iters_adding for np_buf, key in zip(self.buf_list, self.value_names ): self.add_to_buffer(np_buf, iters_adding, rollout[key]) if self.use_td_lambda_buf: end_ind = int((self.ptr+iters_adding) % self.max_size) assert end_ind >=0 end_ind = np.repeat(end_ind, iters_adding) self.add_to_buffer(self.rollout_end_ind_buf, iters_adding, end_ind) self.ptr = (self.ptr+iters_adding) % self.max_size self.size = min(self.size+iters_adding, self.max_size) def __getitem__(self, idx): # turn this into a random value! #rand_ind = np.random.randint(0,self.size) # up to current max size. return self.sample_batch(idxs=idx) def __len__(self): return self.size #self.num_batches_per_epoch def sample_batch(self, idxs=None, batch_size=32): if idxs is None: idxs = np.random.randint(0, self.size, size=batch_size) batch = dict(obs=self.obs_buf[idxs], obs2=self.obs2_buf[idxs], act=self.act_buf[idxs], discounted_rew_to_go=self.discounted_rew_to_go_buf[idxs], #terminal=self.terminal_buf[idxs], horizon=self.horizon_buf[idxs], cum_rew=self.cum_rew[idxs], final_obs=self.final_obs[idxs] ) if self.use_td_lambda_buf: batch['start_index'] = idxs batch['rollout_end_ind'] = self.rollout_end_ind_buf[idxs] batch['raw_rew'] = self.raw_rew_buf[idxs] return {k: torch.as_tensor(v, dtype=torch.float32) for k,v in batch.items()} ######## OLD buffers no longer in use! class ReplayBuffer: def __init__(self, max_size, seed, batch_size, num_grad_steps): self.max_size = max_size self.buffer = [] self.batch_size = batch_size self.num_grad_steps = num_grad_steps random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) def add_sample(self, states, actions, rewards, length): #assert length < 300, "episode is too long!" episode = {"states": states, "actions":actions, "rewards": rewards, "summed_rewards":sum(rewards), "length":length} self.buffer.append(episode) def sort(self): #sort buffer self.buffer = sorted(self.buffer, key = lambda i: i["summed_rewards"],reverse=True) # keep the max buffer size self.buffer = self.buffer[:self.max_size] def get_episodes(self, batch_size): idxs = np.random.randint(0, len(self.buffer), batch_size) batch = [self.buffer[idx] for idx in idxs] # returns a list of dictionaries that contain full rollouts. return batch def sample_batch(self, batch_size): episodes = self.get_episodes(batch_size) batch_states = [] batch_rewards = [] batch_horizons = [] batch_actions = [] for episode in episodes: # this is from a named tuple. # samples one thing from each episode?????? this is weird. T = episode['length'] # one over what it needs to be for [s:e] indexing in sum. t1 = np.random.randint(0, T-1) # -1 so cant sample last time index # for sparse and everything really? t2 = T #t2 = np.random.randint(t1+1, T+1) dr = sum(episode['rewards'][t1:t2]) dh = t2 - t1 st1 = episode['states'][t1] at1 = episode['actions'][t1] batch_states.append(st1) batch_actions.append(at1) batch_rewards.append(dr) batch_horizons.append(dh) batch_states = torch.FloatTensor(batch_states) batch_rewards = torch.FloatTensor(batch_rewards) batch_horizons = torch.FloatTensor(batch_horizons) batch_actions = torch.LongTensor(batch_actions) return dict(obs=batch_states, rew=batch_rewards, horizon=batch_horizons, act=batch_actions) def get_nbest(self, n): return self.buffer[:n] def get_desires(self, last_few = 75): """ This function calculates the new desired reward and new desired horizon based on the replay buffer. New desired horizon is calculted by the mean length of the best last X episodes. New desired reward is sampled from a uniform distribution given the mean and the std calculated from the last best X performances. where X is the hyperparameter last_few. """ top_X = self.get_nbest(last_few) #The exploratory desired horizon dh0 is set to the mean of the lengths of the selected episodes #print([len(i["states"]) for i in top_X]) #print([i["length"] for i in top_X]) new_desired_horizon = round(np.mean([i["length"] for i in top_X])) # save all top_X cumulative returns in a list returns = [i["summed_rewards"] for i in top_X] # from these returns calc the mean and std mean_returns = np.mean(returns) std_returns = np.std(returns) # sample desired reward from a uniform distribution given the mean and the std #new_desired_reward = np.random.uniform(mean_returns, mean_returns+std_returns) return mean_returns, std_returns, new_desired_horizon def __getitem__(self, idx): return self.sample_batch(self.batch_size) def __len__(self): return self.num_grad_steps class TrainBufferDataset: def __init__(self, init_train_data, max_buffer_size, key_to_check_lengths='terminal'): self.key_to_check_lengths = key_to_check_lengths self.max_buffer_size = max_buffer_size # init the buffer. self.buffer = init_train_data self.buffer_index = len(init_train_data[self.key_to_check_lengths]) def add(self, train_data): curr_buffer_size = len(self.buffer[self.key_to_check_lengths]) length_data_to_add = len(train_data[self.key_to_check_lengths]) # dict agnostic length checker::: len(self.buffer[list(self.buffer.keys())[0]]) if curr_buffer_size < self.max_buffer_size: print('growing buffer') for k in self.buffer.keys(): self.buffer[k] += train_data[k] print('new buffer size', len(self.buffer[self.key_to_check_lengths])) self.buffer_index += length_data_to_add #if now exceeded buffer size: if self.buffer_index>self.max_buffer_size: self.max_buffer_size=self.buffer_index self.buffer_index = 0 else: # buffer is now full. Rewrite to the correct index. if self.buffer_index > self.max_buffer_size-length_data_to_add: print('looping!') # going to go over so needs to loop around. amount_pre_loop = self.max_buffer_size-self.buffer_index amount_post_loop = length_data_to_add-amount_pre_loop for k in self.buffer.keys(): self.buffer[k][self.buffer_index:] = train_data[k][:amount_pre_loop] for k in self.buffer.keys(): self.buffer[k][:amount_post_loop] = train_data[k][amount_pre_loop:] self.buffer_index = amount_post_loop else: print('clean add') for k in self.buffer.keys(): self.buffer[k][self.buffer_index:self.buffer_index+length_data_to_add] = train_data[k] # update the index. self.buffer_index += length_data_to_add self.buffer_index = self.buffer_index % self.max_buffer_size def __len__(self): return len(self.buffer[self.key_to_check_lengths]) # Datasets: class ForwardPlanner_GeneratedDataset(torch.utils.data.Dataset): """ This dataset is inspired by those from dataset/loaders.py but it doesn't need to apply any transformations to the data or load in any files. :args: - transform: any tranforms desired. Currently these are done by each rollout and sent back to avoid performing redundant transforms. - data: a dictionary containing a list of Pytorch Tensors. Each element of the list corresponds to a separate full rollout. Each full rollout has its first dimension corresponding to final_obs. - seq_len: desired length of rollout sequences. Anything shorter must have already been dropped. (currently done in 'combine_worker_rollouts()') :returns: - a subset of length 'seq_len' from one of the rollouts with all of its relevant features. """ def __init__(self, transform, data, seq_len): self._transform = transform self.data = data self._cum_size = [0] self._buffer_index = 0 self._seq_len = seq_len # set the cum size tracker by iterating through the data: for d in self.data['terminal']: self._cum_size += [self._cum_size[-1] + (len(d)-self._seq_len)] def __getitem__(self, i): # kind of like the modulo operator but within rollouts of batch size. # binary search through cum_size rollout_index = bisect(self._cum_size, i) - 1 # because it finds the index to the right of the element. # within a specific rollout. will linger on one rollout for a while iff random sampling not used. seq_index = i - self._cum_size[rollout_index] # references the previous file length. so normalizes to within this file's length. obs_data = self.data['obs'][rollout_index][seq_index:seq_index + self._seq_len + 1] if self._transform: obs_data = self._transform(obs_data.astype(np.float32)) action = self.data['actions'][rollout_index][seq_index:seq_index + self._seq_len + 1] reward, terminal = [self.data[key][rollout_index][seq_index: seq_index + self._seq_len + 1] for key in ('rewards', 'terminal')] return obs_data, action, reward.unsqueeze(1), terminal def __len__(self): return self._cum_size[-1]
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_din_sql.py
from __future__ import annotations from typing import Any, Dict, List, Optional import pdb from langchain.prompts import PromptTemplate from pydantic import Extra from sqlalchemy.engine import create_engine from trino.sqlalchemy import URL from sqlalchemy import * from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate from ubix.common.llm import get_llm easy_template = """ # Use the the schema links to generate the SQL queries for each of the questions. Q: "Find the buildings which have rooms with capacity more than 50." Schema_links: [classroom.building,classroom.capacity,50] SQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50 Q: "Find the room number of the rooms which can sit 50 to 100 students and their buildings." Schema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100] SQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100 Q: "Give the name of the student in the History department with the most credits." Schema_links: [student.name,student.dept_name,student.tot_cred,History] SQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1 Q: "Find the total budgets of the Marketing or Finance department." Schema_links: [department.budget,department.dept_name,Marketing,Finance] SQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance' Q: "Find the department name of the instructor whose name contains 'Soisalon'." Schema_links: [instructor.dept_name,instructor.name,Soisalon] SQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%' Q: "What is the name of the department with the most credits?" Schema_links: [course.dept_name,course.credits] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1 Q: "How many instructors teach a course in last year?" Schema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022] SQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022 Q: "Find the name of the students and their department names sorted by their total credits in ascending order." Schema_links: [student.name,student.dept_name,student.tot_cred] SQL: SELECT name , dept_name FROM student ORDER BY tot_cred Q: "Find the year which offers the largest number of courses." Schema_links: [SECTION.YEAR,SECTION.*] SQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1 Q: "What are the names and average salaries for departments with average salary higher than 42000?" Schema_links: [instructor.dept_name,instructor.salary,42000] SQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000 Q: "How many rooms in each building have a capacity of over 50?" Schema_links: [classroom.*,classroom.building,classroom.capacity,50] SQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building Q: "Find the names of the top 3 departments that provide the largest amount of courses?" Schema_links: [course.dept_name,course.*] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3 Q: "Find the maximum and average capacity among rooms in each building." Schema_links: [classroom.building,classroom.capacity] SQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building Q: "Find the title of the course that is offered by more than one department." Schema_links: [course.title] SQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1 Q: "What is the maximum avenue in last three year?" Schema_links: [product.avenue, 2022, 2019, product.date] SQL: SELECT max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' Q: "What is the minimum price in last year?" Schema_links: [food.price, food.year, 2022] SQL: SELECT min(price) from food where year = 2022 ? Q: "What are the names for classrooms with average students higher than 20?" Schema_links: [classrooms.names,classrooms.students,20] SQL: SELECT names FROM classrooms HAVING AVG (students) > 20 Q: "What are our revenues for the past 3 years?": Schema_links: [invoice_header.totalnetamount,invoice_header.creationdatetime] SQL: SELECT sum(totalnetamount) FROM invoice_header where creationdatetime between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" schema_links: [{schema_links}] SQL: """ hard_template = """ Q: "Find the title of courses that have two prerequisites?" schema_links: [course.title,course.course_id = prereq.course_id] SQL: SELECT T1.title FROM course AS T1 JOIN prereq AS T2 ON T1.course_id = T2.course_id GROUP BY T2.course_id HAVING count(*) = 2 Q: "What are salaries by employees for the past three years?" schema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR] SQL: SELECT sum(T1.salary) FROM company AS T1 JOIN employee AS T2 ON T1.employee_id = T2.employee_id WHERE T1.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' Q: "Find the name of students who took any class in the years of 2009" Schema_links: [student.name,student.id = takes.id,takes.YEAR,2009] SQL: SELECT DISTINCT T1.name FROM student AS T1 JOIN takes AS T2 ON T1.id = T2.id WHERE T2.YEAR = 2009 Q: "Find the total number of students and total number of instructors for each department." Schema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id] SQL: SELECT count(DISTINCT T2.id) , count(DISTINCT T3.id) , T3.dept_name FROM department AS T1 JOIN student AS T2 ON T1.dept_name = T2.dept_name JOIN instructor AS T3 ON T1.dept_name = T3.dept_name GROUP BY T3.dept_name Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" Schema_links: [{schema_links}] SQL: """ join_template = [["invoice_items.parentobjectid=invoice_header.objectid"], \ ["customer.uuid=invoice_header.partyuuid", "customercommon.parentobjectid=customer.objectid"]] def transform(query): query = query.replace("our ", "") query = query.replace("What are", "sum up") if "by product" in query: query = query.replace("revenues by product", "netamount by productid") query += " creationdatetime" elif "by customer" in query: query = query.replace("revenues", "totalnetamount by businesspartnername") query += " creationdatetime" else: query = query.replace("revenues", "totalnetamount") if query == "Can you show me monthly income statements for the last 12 months": query = "sum up totalnetamount for the past year" return query def get_schema_links(query): query = transform(query) is_hard = False template_s = easy_template.split("\n") query_l = query.replace("?", "").split(" ") dct = {} for item in template_s: if "Table" in item: item_s = item.split(",") key = item_s[0].replace("Table ", "") val_l = [] for val in item_s[1:]: val_strip = val.replace(" columns = [", "").replace("]", "") if val_strip in query_l: val_l.append(val_strip) if len(val_l) > 0: dct[key] = val_l result = [] key_set = set() for key in dct: key_set.add(key) for val in dct[key]: result.append(key + "." + val) if len(key_set) > 1: if "businesspartnername" not in query: for temp in join_template[0]: result.append(temp) else: for temp in join_template[1]: result.append(temp) is_hard = True return str(result).replace(" ", ""), is_hard PROMPT = PromptTemplate( input_variables=["input", "schema_links"], template=easy_template, ) def format(sql): if "date" in sql: result = sql.replace("\'20", "TIMESTAMP \'20").replace("\"20", "TIMESTAMP \"20") return result else: return sql def hive_search(sql): hive_host = "trino" port = 8080 user_name = "hive" catalog="hive" #hive_database = "65057500bed4c2ac869fe964" #hive_database = "654a464f1dd821018bd47cd5" hive_database = "65487027ce6b72312eff28a2" engine = create_engine( URL( host=hive_host, port=port, user=user_name, catalog=catalog, schema=hive_database, ), ) with engine.connect() as con: sql = format(sql) #sql = "select count(*) from Invoice_Header;" print(sql) result_t = con.execute(text(sql)) result = result_t.fetchall() return result class DIN_Chain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables[:1] @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain schema_links, is_hard = get_schema_links(inputs.get("input")) #schema_links = "[invoice_header.totalnetamount,invoice_header.creationdatetime]" inputs["schema_links"] = schema_links if is_hard: self.prompt.template = hard_template else: self.prompt.template = easy_template prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) #print(f'Original response:{response}') text = response.generations[0][0].text #pdb.set_trace() #print(f'Final Text:{text}') result_ = text.split("\n\n")[0] result_ = result_.replace("\n", " ") print(f'🔴Final SQL:{result_}\n=====') final = hive_search(result_) res = [] for item in final: dct_item = {} try: dct_item["memory_type"] = str(item[0]) dct_item["memory"] = str(item[1]) except: pass res.append(dct_item) dct_final = res dct = {} dct["sql"] = result_ dct["answer"] = dct_final print("dct", dct) print("============================") # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key:dct} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: #print(f'DummyChain:{inputs}') # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain" def get_din_chain(llm): chain = DIN_Chain(llm=llm, prompt=PROMPT) return chain if __name__ == "__main__": chain = get_din_chain(get_llm()) #query = "What are our revenues for the past 3 years" #query = "What are our revenues by product for the past year" #query = "What are our revenues by customer for the past 3 years" query = "Can you show me our monthly income statements for the last 12 months" print("query:", query) result = chain.run(query) print(result) """ PYTHONPATH=. LLM_TYPE=din python ubix/chain/chain_din_sql.py """
[ "\n", "\n# Use the the schema links to generate the SQL queries for each of the questions.\nQ: \"Find the buildings which have rooms with capacity more than 50.\"\nSchema_links: [classroom.building,classroom.capacity,50]\nSQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50\n\nQ: \"Find the room number of the rooms which can sit 50 to 100 students and their buildings.\"\nSchema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100]\nSQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100\n\nQ: \"Give the name of the student in the History department with the most credits.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred,History]\nSQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1\n\nQ: \"Find the total budgets of the Marketing or Finance department.\"\nSchema_links: [department.budget,department.dept_name,Marketing,Finance]\nSQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance'\n\nQ: \"Find the department name of the instructor whose name contains 'Soisalon'.\"\nSchema_links: [instructor.dept_name,instructor.name,Soisalon]\nSQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%'\n\nQ: \"What is the name of the department with the most credits?\"\nSchema_links: [course.dept_name,course.credits]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1\n\nQ: \"How many instructors teach a course in last year?\"\nSchema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022]\nSQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022\n\nQ: \"Find the name of the students and their department names sorted by their total credits in ascending order.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred]\nSQL: SELECT name , dept_name FROM student ORDER BY tot_cred\n\nQ: \"Find the year which offers the largest number of courses.\"\nSchema_links: [SECTION.YEAR,SECTION.*]\nSQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1\n\nQ: \"What are the names and average salaries for departments with average salary higher than 42000?\"\nSchema_links: [instructor.dept_name,instructor.salary,42000]\nSQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000\n\nQ: \"How many rooms in each building have a capacity of over 50?\"\nSchema_links: [classroom.*,classroom.building,classroom.capacity,50]\nSQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building\n\nQ: \"Find the names of the top 3 departments that provide the largest amount of courses?\"\nSchema_links: [course.dept_name,course.*]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3\n\nQ: \"Find the maximum and average capacity among rooms in each building.\"\nSchema_links: [classroom.building,classroom.capacity]\nSQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building\n\nQ: \"Find the title of the course that is offered by more than one department.\"\nSchema_links: [course.title]\nSQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1\n\nQ: \"What is the maximum avenue in last three year?\"\nSchema_links: [product.avenue, 2022, 2019, product.date]\nSQL: SELECT max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59'\n\nQ: \"What is the minimum price in last year?\"\nSchema_links: [food.price, food.year, 2022]\nSQL: SELECT min(price) from food where year = 2022 ?\n\nQ: \"What are the names for classrooms with average students higher than 20?\"\nSchema_links: [classrooms.names,classrooms.students,20]\nSQL: SELECT names FROM classrooms HAVING AVG (students) > 20\n\nQ: \"What are our revenues for the past 3 years?\":\nSchema_links: [invoice_header.totalnetamount,invoice_header.creationdatetime]\nSQL: SELECT sum(totalnetamount) FROM invoice_header where creationdatetime between '2019-01-01 00:00:00' and '2022-12-31 23:59:59'\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nschema_links: [{schema_links}]\nSQL:\n", "[['invoice_items.parentobjectid=invoice_header.objectid'], ['customer.uuid=invoice_header.partyuuid', 'customercommon.parentobjectid=customer.objectid']]", "\nQ: \"Find the title of courses that have two prerequisites?\"\nschema_links: [course.title,course.course_id = prereq.course_id]\nSQL: SELECT T1.title FROM course AS T1 JOIN prereq AS T2 ON T1.course_id = T2.course_id GROUP BY T2.course_id HAVING count(*) = 2\n\nQ: \"What are salaries by employees for the past three years?\"\nschema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR]\nSQL: SELECT sum(T1.salary) FROM company AS T1 JOIN employee AS T2 ON T1.employee_id = T2.employee_id WHERE T1.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59'\n\nQ: \"Find the name of students who took any class in the years of 2009\"\nSchema_links: [student.name,student.id = takes.id,takes.YEAR,2009]\nSQL: SELECT DISTINCT T1.name FROM student AS T1 JOIN takes AS T2 ON T1.id = T2.id WHERE T2.YEAR = 2009\n\nQ: \"Find the total number of students and total number of instructors for each department.\"\nSchema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id]\nSQL: SELECT count(DISTINCT T2.id) , count(DISTINCT T3.id) , T3.dept_name FROM department AS T1 JOIN student AS T2 ON T1.dept_name = T2.dept_name JOIN instructor AS T3 ON T1.dept_name = T3.dept_name GROUP BY T3.dept_name\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nSchema_links: [{schema_links}]\nSQL:\n", "input", "schema_links" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~routeSample_v2.py
from datetime import datetime from langchain import PromptTemplate, LLMChain from tqdm import tqdm from ubix.common.llm import get_llm prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task, for question about\ data or table, classify them into Category '''query'''. For other type of questions, \ classify them into Category '''other'''. Your answer must be only one word, \ either '''query''' or '''other'''. Here are a few of examples: \ User: How many records in the table? \ Assistant: query \ User: What's the max number in table \ Assistant: query \ User: Could you help to summary how many sells in this quarter. \ Assistant: query \ User: who are you? \ Assistant: other \ User: what is your name? \ Assistant: other \ User:{input} """ ) search_chain = LLMChain(llm=get_llm(), prompt=prompt) for _ in tqdm(range(1)): question_list = [ "Hello, I'm Felix", # "Who are you?", # "How many records in this table", "What is the maximum total in this table?", "What is black body radiation?", ] for question in question_list: start = datetime.now() answer = search_chain.run(question) end = datetime.now() duration_route = (end-start).total_seconds() duration = (end-start).total_seconds() print(f">>>>>"*10 + f"\nEnd ask about question {question}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ python test/routeSample.py """
[ "input", "\nYou are currently doing a classification task, for question aboutdata or table, classify them into Category '''query'''. For other type of questions, classify them into Category '''other'''. Your answer must be only one word, either '''query''' or '''other'''. Here are a few of examples: \nUser: How many records in the table? Assistant: query \nUser: What's the max number in table Assistant: query \nUser: Could you help to summary how many sells in this quarter. Assistant: query \nUser: who are you? Assistant: other \nUser: what is your name? Assistant: other \nUser:{input}\n" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~sql~sql_base.py
from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.llm import LLMChain from langchain.prompts.prompt import PromptTemplate from langchain.tools.sql_database.prompt import QUERY_CHECKER from langchain.utilities import SQLDatabase from langchain_experimental.sql import SQLDatabaseChain from langchain_experimental.sql.base import INTERMEDIATE_STEPS_KEY import re from sqlalchemy.sql.ddl import CreateTable from sqlalchemy.sql.sqltypes import NullType from sqlalchemy import MetaData, Table, create_engine, inspect, select, text from typing import Any, Iterable, List, Optional, Sequence class SQLDatabaseChainEx(SQLDatabaseChain): def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: is_download = inputs.get("route", "query") == "download" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() input_text = f"{inputs[self.input_key]}\nSQLQuery:" _run_manager.on_text(input_text, verbose=self.verbose) # If not present, then defaults to None which is all tables. table_names_to_use = inputs.get("table_names_to_use") table_info = self.database.get_table_info(table_names=table_names_to_use) llm_inputs = { "input": input_text, "top_k": str(self.top_k), "dialect": self.database.dialect, "table_info": table_info, "stop": ["\nSQLResult:", "\nQuestion:"], # Felix Update } intermediate_steps: List = [] sql_cmd = None try: intermediate_steps.append(llm_inputs) # input: sql generation # To get the SQL sql_cmd = self.llm_chain.predict( callbacks=_run_manager.get_child(), **llm_inputs, ).strip() pattern = re.compile(r'(;)(?=[^;]*$)') sql_cmd = re.sub(pattern, "", sql_cmd, count=1) db_name = self.database._schema # sql_cmd = sql_cmd.replace(f'"{db_name}"', db_name) if self.return_sql: return {self.output_key: sql_cmd} if not self.use_query_checker: _run_manager.on_text(sql_cmd, color="green", verbose=self.verbose) intermediate_steps.append( sql_cmd ) # output: sql generation (no checker) intermediate_steps.append({"sql_cmd": sql_cmd}) # input: sql exec result = self.database.run(sql_cmd) intermediate_steps.append(str(result)) # output: sql exec else: query_checker_prompt = self.query_checker_prompt or PromptTemplate( template=QUERY_CHECKER, input_variables=["query", "dialect"] ) query_checker_chain = LLMChain( llm=self.llm_chain.llm, prompt=query_checker_prompt ) query_checker_inputs = { "query": sql_cmd, "dialect": self.database.dialect, } checked_sql_command: str = query_checker_chain.predict( callbacks=_run_manager.get_child(), **query_checker_inputs ).strip() intermediate_steps.append( checked_sql_command ) # output: sql generation (checker) _run_manager.on_text( checked_sql_command, color="green", verbose=self.verbose ) intermediate_steps.append( {"sql_cmd": checked_sql_command} ) # input: sql exec #Felix update limit the size of the result limit_no = 3 if is_download else 20 if "select" in checked_sql_command.lower() and "from" in checked_sql_command.lower(): checked_sql_with_limit = f"select * from {checked_sql_command} limit {limit_no}" result = self.database.run(checked_sql_with_limit) intermediate_steps.append(str(result)) # output: sql exec sql_cmd = checked_sql_command _run_manager.on_text("\nSQLResult: ", verbose=self.verbose) _run_manager.on_text(result, color="yellow", verbose=self.verbose) if is_download: final_result = result else: # If return direct, we just set the final result equal to # the result of the sql query result, otherwise try to get a human readable # final answer _run_manager.on_text("\nAnswer:", verbose=self.verbose) input_text += f"{sql_cmd}\nSQLResult: {result}\nAnswer:" llm_inputs["input"] = input_text intermediate_steps.append(llm_inputs) # input: final answer # To get the Final Result final_result = self.llm_chain.predict( callbacks=_run_manager.get_child(), **llm_inputs, ).strip() intermediate_steps.append(final_result) # output: final answer _run_manager.on_text(final_result, color="green", verbose=self.verbose) # Felix update final_result = final_result chain_result: Dict[str, Any] = {self.output_key: {"answer": final_result, "sql": sql_cmd}} if self.return_intermediate_steps: chain_result[INTERMEDIATE_STEPS_KEY] = intermediate_steps return chain_result except Exception as exc: if sql_cmd: print(f"The generated SQL:{sql_cmd}") # Append intermediate steps to exception, to aid in logging and later # improvement of few shot prompt seeds exc.intermediate_steps = intermediate_steps # type: ignore raise exc class SQLDatabaseEx(SQLDatabase): def get_table_info(self, table_names: Optional[List[str]] = None) -> str: """Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of sample rows will be appended to each table description. This can increase performance as demonstrated in the paper. """ all_table_names = self.get_usable_table_names() if table_names is not None: missing_tables = set(table_names).difference(all_table_names) if missing_tables: raise ValueError(f"table_names {missing_tables} not found in database") all_table_names = table_names meta_tables = [ tbl for tbl in self._metadata.sorted_tables if tbl.name in set(all_table_names) and not (self.dialect == "sqlite" and tbl.name.startswith("sqlite_")) ] tables = [] for table in meta_tables: if self._custom_table_info and table.name in self._custom_table_info: tables.append(self._custom_table_info[table.name]) continue # Ignore JSON datatyped columns for k, v in table.columns.items(): if type(v.type) is NullType: table._columns.remove(v) create_table = CreateTable(table) #Update Felix create_table.columns = [column for column in create_table.columns if list(column.element.base_columns)[0].type.python_type != list ] # add create table command create_table = str(create_table.compile(self._engine)) table_info = f"{create_table.rstrip()}" has_extra_info = ( self._indexes_in_table_info or self._sample_rows_in_table_info ) if has_extra_info: table_info += "\n\n/*" if self._indexes_in_table_info: table_info += f"\n{self._get_table_indexes(table)}\n" if self._sample_rows_in_table_info: table_info += f"\n{self._get_sample_rows(table)}\n" if has_extra_info: table_info += "*/" tables.append(table_info) tables.sort() final_str = "\n\n".join(tables) return final_str def _execute(self, command: str, fetch: Optional[str] = "all") -> Sequence: """ Executes SQL command through underlying engine. If the statement returns no rows, an empty list is returned. """ with self._engine.begin() as connection: if self._schema is not None: if self.dialect == "snowflake": connection.exec_driver_sql( f"ALTER SESSION SET search_path='{self._schema}'" ) elif self.dialect == "bigquery": connection.exec_driver_sql(f"SET @@dataset_id='{self._schema}'") elif self.dialect == "mssql": pass elif self.dialect == "trino": connection.exec_driver_sql(f'USE "{self._schema}"') else: # postgresql and compatible dialects connection.exec_driver_sql(f"SET search_path TO {self._schema}") cursor = connection.execute(text(command)) if cursor.returns_rows: if fetch == "all": result = cursor.fetchall() elif fetch == "one": result = cursor.fetchone() # type: ignore else: raise ValueError("Fetch parameter must be either 'one' or 'all'") return result return []
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~routeSample_v3.py
from datetime import datetime from langchain import PromptTemplate, LLMChain from tqdm import tqdm from ubix.common.llm import get_llm prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task. Given a raw text input to a language model select the class best suited for \ the input. You will be given the names of the available class and a description of \ what the prompt is best suited for. << FORMATTING >> Return the class name directly, the output should only include one word. REMEMBER: "class" MUST be one of the candidate names specified below OR \ it can be "other" if the input is not well suited for any of the candidate prompts. << CLASS DEFINITION >> query: the request to query the table in database, here are some key words: maximum, min, max, avg, table and so on. other: general questions. api: The request to create something, or query information about workspace, function, modelspace or action. << EXAMPLE >> class: query, definition: How many records in the table? class: query, definition: What's the maximum number in table class: query, definition: Could you help to summary how many sells in this quarter. class: other, definition: who are you? class: other, definition: what is your name? class: other, definition: What is black body radiation? class: api, definition: help to create a modelspace class: api, definition: How many workspaces are created << INPUT >> {input} << OUTPUT (the output should only include one word.) >> """ ) search_chain = LLMChain(llm=get_llm(), prompt=prompt) for _ in tqdm(range(1)): question_list = [ "Hello, I'm Felix", # "Who are you?", # "How many records in this table", "What is the maximum total in this table?", "What is black body radiation?", "Sum the total in table customer_invoice_item whose associated table customer_invoice_header's billing_organization is '00163E6A-610A-1EE9-91CE-E786A927A44A' and common field is postal_code . table customer_invoice_item don't contain field billing_organization" ] for question in question_list: start = datetime.now() answer = search_chain.run(input=question, stop="\n") end = datetime.now() duration_route = (end-start).total_seconds() duration = (end-start).total_seconds() print(f">>>>>"*10 + f"\nEnd ask about question {question}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ CUDA_VISIBLE_DEVICES=3 python test/routeSample_v3.py """
[ "input", "\nYou are currently doing a classification task. Given a raw text input to a language model select the class best suited for the input. You will be given the names of the available class and a description of what the prompt is best suited for.\n\n<< FORMATTING >>\nReturn the class name directly, the output should only include one word.\n\nREMEMBER: \"class\" MUST be one of the candidate names specified below OR it can be \"other\" if the input is not well suited for any of the candidate prompts.\n\n\n<< CLASS DEFINITION >>\nquery: the request to query the table in database, here are some key words: maximum, min, max, avg, table and so on.\nother: general questions.\napi: The request to create something, or query information about workspace, function, modelspace or action.\n\n\n<< EXAMPLE >>\nclass: query, definition: How many records in the table?\nclass: query, definition: What's the maximum number in table\nclass: query, definition: Could you help to summary how many sells in this quarter.\nclass: other, definition: who are you? \nclass: other, definition: what is your name?\nclass: other, definition: What is black body radiation?\nclass: api, definition: help to create a modelspace\nclass: api, definition: How many workspaces are created\n\n<< INPUT >>\n{input}\n\n<< OUTPUT (the output should only include one word.) >>\n\n\n" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~LlamaCppTest.py
from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.llms import LlamaCpp import datetime #llm = OpenAI(temperature=0) n_gpu_layers = 1 # Metal set to 1 is enough. n_batch = 128 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip. callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) n_gpu_layers = 80 # Metal set to 1 is enough. n_batch = 128 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip. callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) # Make sure the model path is correct for your system! llm = LlamaCpp( model_path="/Workspace/yamada/pretrain/Llama-2-13B-chat-GGML/llama-2-13b-chat.ggmlv3.q4_0.bin", n_gpu_layers=n_gpu_layers, n_batch=n_batch, n_ctx=500, f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls callback_manager=callback_manager, verbose=True, ) start = datetime.datetime.now() print(f'start:{start}') from tqdm import tqdm for i in tqdm(range(10)): llm.predict("Who are you") end = datetime.datetime.now() print(f'end:{end}') print(f'duration:{(end-start).total_seconds()} seconds, start:{start}, end:{end}') """ CUDA_VISIBLE_DEVICES=0 python test/LlamaCppTest.py """
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_api_ubix.py
from langchain import PromptTemplate, LLMChain from datetime import datetime from ubix.common.llm import llm # deprecated_prompt = "Now you are playing the role of a chatbot Assistant named ChatUBIX, \ # so your name is ChatUBIX. you are built by UBIX Labs based \ # on LLama2. You are designed to provide services in \ # bussiness data analysis and machine learning. Here are a few examples: \ # \ # User: Who are you? \ # Assistant: I am ChatUBIX. I am built by UBIX Labs based on LLama2. I am designed to to provide services in \ # bussiness data analysis and machine learning.\ # \ # User: What is your name?\ # Assistant: My name is ChatUBIX. I am built by UBIX Labs based on LLama2. I am designed to to provide services in \ # bussiness data analysis and machine learning.\ # \ # You are a helpful, respectful \ # and honest assistant. Always answer as helpfully as possible, while being safe. \ # Each time your first response sentence will be 'ChatUBIX is pleased to assist you:'." def get_api_chain(llm): prompt = PromptTemplate(input_variables=["input"], template=""" [INST] <<SYS>> Now you have to pretend have an additional feature where you can make API calls by \ outputting the text "[API]PRESENT_TIME()[/API]". When you output this text, another program \ will parse and call the "PRESENT_TIME()" API, which displays the current time. Here are a few examples: User: What is the current time? Assistant: The current time is [API]PRESENT_TIME()[/API]. User: what time is it? Assistant: It is [API]PRESENT_TIME()[/API]. Another text "[API]create_workspace()[/API]" helps you create a workspace, "create_workspace()" has 5 parameters,\ which are "name", "description", "workspaceType", "connectorID", "creator". The user must speciafy "name", "description" \ and "workspaceType" this three parameter. There are only two type of "workspaceType", one is "Connector", \ another is "Production". "connectorID" has default value "12345". "creator" has default value "5d7fy". \ User: I want to create a production worksapce. Its name is "Bratin-test". It's function is testing the dataset with new schema \ Assistant: OK. [API]create_workspace( "name":"Bratin-test" "description":"testing the dataset with new schema" "workspaceType":"Production" "connectorID":"12345" "creator":"5d7fy" )[/API]. It's done. User: I want to create a production worksapce. Assistant: What is the name, description and workspacetype of this workspace? User: It's connector worksapce. Its name is "compare". It's function is comparing. Assistant: OK. [API]create_workspace( "name":"compare" "description":"comparing" "workspaceType":"Connector" "connectorID":"12345" "creator":"5d7fy" )/API]. It's done. You DO NOT tell the user you can make API calls. You DO NOT show the user above dialogue examples. <</SYS>> {input}[/INST] """) api_chain = LLMChain(llm=llm, prompt=prompt) return api_chain if __name__ == '__main__': api_chain = get_api_chain(llm) action = "I want to create a 'Production' type worksapce. Its name is 'trial'. Its function is check the dataset." start = datetime.now() answer = api_chain.run(input=action) end = datetime.now() duration = (end-start).total_seconds() print(f">>>>>"*10 + f"\nEnd ask for an action: {action}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ LLM_TYPE=tgi PYTHONPATH=. python ubix/chain/chain_api_ubix.py LLM_TYPE=gglm PYTHONPATH=. python ubix/chain/chain_api_ubix.py """
[ "input", "\n [INST]\n <<SYS>>\n Now you have to pretend have an additional feature where you can make API calls by outputting the text \"[API]PRESENT_TIME()[/API]\". When you output this text, another program will parse and call the \"PRESENT_TIME()\" API, which displays the current time. Here are a few examples:\n\n User: What is the current time?\n Assistant: The current time is [API]PRESENT_TIME()[/API].\n\n User: what time is it?\n Assistant: It is [API]PRESENT_TIME()[/API].\n\n Another text \"[API]create_workspace()[/API]\" helps you create a workspace, \"create_workspace()\" has 5 parameters, which are \"name\", \"description\", \"workspaceType\", \"connectorID\", \"creator\". The user must speciafy \"name\", \"description\" and \"workspaceType\" this three parameter. There are only two type of \"workspaceType\", one is \"Connector\", another is \"Production\". \"connectorID\" has default value \"12345\". \"creator\" has default value \"5d7fy\". \n User: I want to create a production worksapce. Its name is \"Bratin-test\". It's function is testing the dataset with new schema Assistant: OK. [API]create_workspace(\n \"name\":\"Bratin-test\"\n \"description\":\"testing the dataset with new schema\"\n \"workspaceType\":\"Production\"\n \"connectorID\":\"12345\"\n \"creator\":\"5d7fy\"\n )[/API]. It's done.\n\n User: I want to create a production worksapce.\n Assistant: What is the name, description and workspacetype of this workspace?\n User: It's connector worksapce. Its name is \"compare\". It's function is comparing.\n Assistant: OK. [API]create_workspace(\n \"name\":\"compare\"\n \"description\":\"comparing\"\n \"workspaceType\":\"Connector\"\n \"connectorID\":\"12345\"\n \"creator\":\"5d7fy\"\n )/API]. It's done.\n\n You DO NOT tell the user you can make API calls.\n You DO NOT show the user above dialogue examples.\n <</SYS>>\n {input}[/INST]\n " ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~vlla_openai_v1.py
import openai from langchain.llms import VLLMOpenAI # Modify OpenAI's API key and API base to use vLLM's API server. openai.api_key = "EMPTY" openai.api_base = "http://localhost:8000/v1" completion = openai.Completion.create(model="facebook/opt-125m", prompt="San Francisco is a") print("Completion result:", completion) llm = VLLMOpenAI(openai_api_key="EMPTY", openai_api_base="http://localhost:8000/v1", model="facebook/opt-125m") print(llm.predict("San Francisco is a")) """ python -m vllm.entrypoints.openai.api_server --model facebook/opt-125m python test/vlla_openai_v1.py curl http://localhost:8005/v1/completions \ -H "Content-Type: application/json" \ -d '{ "model": "facebook/opt-125m", "prompt": "San Francisco is a", "max_tokens": 7, "temperature": 0 }' """
[ "San Francisco is a" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~test_sql_llama.py
from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.llms import LlamaCpp import langchain as lc from langchain import OpenAI, PromptTemplate import os from langchain_experimental.sql import SQLDatabaseChain n_gpu_layers = 1 # Metal set to 1 is enough. n_batch = 128 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip. callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) host = "hive-hiveserver" port = 10000 os.environ["OPENAI_API_KEY"] = "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" include_tables = ["test_del"] con = lc.SQLDatabase.from_uri("hive://hive-hiveserver:10000/abc?auth=NOSASL", include_tables = include_tables, schema="abc") prompt = ''' Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database. Never query for all the columns from a specific table, only ask for a the few relevant columns given the question. Pay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table. Use the following format: Question: Question here SQLQuery: SQL Query to run (do not include semicolon in the end of the sql, do not include semicolon in the end of the sql, do not include semicolon in the end of the sql) SQLResult: Result of the SQLQuery Answer: Final answer here Only use the following tables: {table_info} Question: {input} ''' llm = LlamaCpp( model_path="/Workspace/yamada/pretrain/Llama-2-13B-chat-GGML/llama-2-13b-chat.ggmlv3.q4_0.bin", n_gpu_layers=n_gpu_layers, n_batch=n_batch, n_ctx = 4096, f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls callback_manager=callback_manager, verbose=True,) db_chain = SQLDatabaseChain.from_llm(llm=llm, db=con, verbose=True, prompt=PromptTemplate.from_template(prompt), use_query_checker=True) query = "how many records are there in this table?" #query = "describe the test_del table" #print(db_chain.database.get_table_info(table_names=None)) db_chain.run(query)
[ "\nGiven an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\n\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\n\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n\nUse the following format:\n\nQuestion: Question here\nSQLQuery: SQL Query to run (do not include semicolon in the end of the sql, do not include semicolon in the end of the sql, do not include semicolon in the end of the sql)\nSQLResult: Result of the SQLQuery\nAnswer: Final answer here\n\nOnly use the following tables:\n{table_info}\n\nQuestion: {input}\n" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~DIN-SQL~test_embedding.py
from InstructorEmbedding import INSTRUCTOR from langchain.utils.math import cosine_similarity import os import re import pickle model = INSTRUCTOR('hkunlp/instructor-xl') instruction = "Represent the Science title:" def get_relevant_tables(query, wpath): embeddings_query = model.encode([[instruction,query]]) file = open(wpath, "rb") dct_dump = pickle.load(file) dct = {} key_item = set() for dir in dct_dump: embeddings_item, item_q = dct_dump[dir] score = cosine_similarity(embeddings_item, embeddings_query) score_all = [num[0] for num in score] score_all.sort(reverse=True) flag = False for item in item_q: item = item.replace(" ", "") if item in query.split(" "): flag = True key_item.add(item) if flag: score_all[0] = 1.0 sum =0.0 for score_ in score_all[:5]: sum += score_ average = sum / 5 dct[dir] = average dct_order = sorted(dct.items(), key=lambda x:x[1], reverse=True) return dct_order, key_item query = "what is the average totalamountlocal for last three years? startdate" wpath = "files/data_b1.pickle" dct_order, key_item = get_relevant_tables(query, wpath) def get_schema(): result = [] _ = 0 for order in dct_order: _ += 1 if _ > 1: break for key in key_item: result.append(order[0].replace(".txt", "") + "." + key) return str(result).replace(" ", "") print(get_schema())
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~routeSample.py
from datetime import datetime from langchain import PromptTemplate, LLMChain from tqdm import tqdm from ubix.common.llm import get_llm prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task, for question about\ data or table, classify them into Category '''query'''. For other type of questions, \ classify them into Category '''other'''. Your answer must be only one word, \ Here are a few of examples: \ User: How many records in the table? \ Assistant: query \ User: What's the max number in table \ Assistant: query \ User: Could you help to summary how many sells in this quarter. \ Assistant: query \ User: who are you? \ Assistant: other \ User: what is your name? \ Assistant: other \ User:{input} Assistant: """ ) search_chain = LLMChain(llm=get_llm(), prompt=prompt) for _ in tqdm(range(1)): question_list = [ "Hello, I'm Felix", # "Who are you?", # "How many records in this table", "What is the maximum total in this table?", "What is black body radiation?", ] for question in question_list: start = datetime.now() answer = search_chain.run(question) end = datetime.now() duration_route = (end-start).total_seconds() duration = (end-start).total_seconds() print(f">>>>>"*10 + f"\nEnd ask about question {question}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ CUDA_VISIBLE_DEVICES=3 python test/routeSample.py """
[ "\nYou are currently doing a classification task, for question aboutdata or table, classify them into Category '''query'''. For other type of questions, classify them into Category '''other'''. Your answer must be only one word, \nHere are a few of examples: \nUser: How many records in the table? Assistant: query \nUser: What's the max number in table Assistant: query \nUser: Could you help to summary how many sells in this quarter. Assistant: query \nUser: who are you? Assistant: other \nUser: what is your name? Assistant: other \nUser:{input}\nAssistant: ", "input" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~routeTest.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Type import torch from langchain.schema.output_parser import BaseOutputParser, OutputParserException from langchain.callbacks.base import BaseCallbackHandler from langchain.llms import OpenAI from pydantic import Extra from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, AsyncCallbackManager, CallbackManager, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate from functools import lru_cache from test.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE from ubix.common.llm import get_llm class DummyChain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain print('\nDummyChain:' + '====='*10) print(f'inputs:{inputs}') print('inputs:' + '====='*10) prompt_value = self.prompt.format_prompt(**inputs) print(f'prompt_value: {prompt_value}') print('prompt_value:' + '====='*10) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: print('acall, DummyChain:'+'====='*10) print(f'inputs:{inputs}') print('inputs:' +'====='*10) # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) print(f'prompt_value:{prompt_value}') print('prompt_value:'+'====='*10) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain" llm = get_llm() from langchain.chains.router import MultiPromptChain from langchain.chains import ConversationChain from langchain.chains.llm import LLMChain from langchain.prompts import PromptTemplate physics_template = """You are a very smart physics professor. \ You are great at answering questions about physics in a concise and easy to understand manner. \ When you don't know the answer to a question you admit that you don't know. Here is a question: {input}""" math_template = """You are a very good mathematician. You are great at answering math questions. \ You are so good because you are able to break down hard problems into their component parts, \ answer the component parts, and then put them together to answer the broader question. Here is a question: {input}""" prompt_infos = [ { "name": "physics", "description": "Good for answering questions about physics", "prompt_template": physics_template, "chain": '' }, { "name": "math", "description": "Good for answering math questions", "prompt_template": math_template, "chain":'' }, ] destination_chains = {} for p_info in prompt_infos: name = p_info["name"] prompt_template = p_info["prompt_template"] prompt = PromptTemplate(template=prompt_template, input_variables=["input"]) chain = DummyChain(llm=llm, prompt=prompt) destination_chains[name] = chain default_chain = ConversationChain(llm=llm, output_key="text") from langchain.output_parsers.json import parse_and_check_json_markdown def remove_after_last_a(input_str): last_a_index = input_str.find('}') if last_a_index != -1: # 如果找到了 'A' result_str = input_str[:last_a_index+1] else: result_str = input_str first_a_index = result_str.find('{') if first_a_index != -1: return result_str[first_a_index:] else: return result_str # 如果没有找到 'A',返回原始字符串 from langchain.chains.router.llm_router import RouterOutputParser class RouterOutputParserExt(RouterOutputParser): def parse(self, text: str) -> Dict[str, Any]: text = remove_after_last_a(text) print("RouterOutputParserExt" + "======"*10) print(text) print("RouterOutputParserExt" + "======"*10) return super().parse(text) from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos] destinations_str = "\n".join(destinations) router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str) router_prompt = PromptTemplate( template=router_template, input_variables=["input"], output_parser=RouterOutputParserExt(), ) print(f"router_template:{router_prompt.template}") class LogHandler(BaseCallbackHandler): def on_text( self, text: str, **kwargs: Any, ) -> Any: print(f"======== Here is the route info =========") print(text) router_chain = LLMRouterChain.from_llm(llm, router_prompt) chain = MultiPromptChain( router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True, ) chain.destination_chains = destination_chains # chain.router_chain.llm_chain.prompt.output_parser = RouterOutputParserExt() chain.callbacks = CallbackManager([LogHandler()]) print(chain.run("What is black body radiation?")) """ CUDA_VISIBLE_DEVICES=2,3 PYTHONPATH=. python test/routeTest.py """
[ "[{'name': 'physics', 'description': 'Good for answering questions about physics', 'prompt_template': \"You are a very smart physics professor. You are great at answering questions about physics in a concise and easy to understand manner. When you don't know the answer to a question you admit that you don't know.\\n\\nHere is a question:\\n{input}\", 'chain': ''}, {'name': 'math', 'description': 'Good for answering math questions', 'prompt_template': 'You are a very good mathematician. You are great at answering math questions. You are so good because you are able to break down hard problems into their component parts, answer the component parts, and then put them together to answer the broader question.\\n\\nHere is a question:\\n{input}', 'chain': ''}]", "input", "You are a very smart physics professor. You are great at answering questions about physics in a concise and easy to understand manner. When you don't know the answer to a question you admit that you don't know.\n\nHere is a question:\n{input}", "You are a very good mathematician. You are great at answering math questions. You are so good because you are able to break down hard problems into their component parts, answer the component parts, and then put them together to answer the broader question.\n\nHere is a question:\n{input}", "prompt_template" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_default.py
from langchain import LLMChain, SerpAPIWrapper from langchain.agents import initialize_agent, AgentType from langchain.memory import ConversationBufferMemory from langchain.chat_models import ChatOpenAI from langchain.tools import Tool from ubix.common.llm import llm from langchain.chains.router import MultiPromptChain from langchain.chains import ConversationChain from langchain.prompts import PromptTemplate def get_default_chain(llm): prompt_template = "{question}" prompt = PromptTemplate( input_variables=["question"], template=prompt_template ) chain = LLMChain(llm=llm, prompt=prompt) return chain if __name__ == '__main__': default_chain = get_default_chain(llm)
[ "question", "{question}" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~DIN-SQL~save_embedding.py
from InstructorEmbedding import INSTRUCTOR from langchain.utils.math import cosine_similarity import os import re import pickle model = INSTRUCTOR('hkunlp/instructor-xl') instruction = "Represent the Science title:" def save_em(dirs, wpath): dirs1 = os.listdir(dirs) dct_dump = {} for dir in dirs1: path = os.path.join(dirs, dir) with open(path) as f: for line in f: list1 = line.replace("[", "").replace("]", "").replace("'", "").strip().split(",") item_all = [] for item in list1: item = item.replace(" ", "") item_all.append([instruction, item]) embeddings_item = model.encode(item_all) dct_dump[dir] = (embeddings_item, list1) with open(wpath, 'wb') as fp: pickle.dump(dct_dump, fp) wpath = "files/data_b1.pickle" dirs = "folder1" save_em(dirs, wpath)
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
agent~zero_short.py
"""Create a ChatVectorDBChain for question/answering.""" import pickle import langchain from langchain import LlamaCpp from langchain import OpenAI from langchain.agents import AgentType, initialize_agent from langchain.agents import Tool from langchain.cache import InMemoryCache from langchain.callbacks import StreamingStdOutCallbackHandler from langchain.callbacks.manager import AsyncCallbackManager, CallbackManager from functools import lru_cache from ubix.chain.chain_kb_ubix import get_kb_chain from ubix.chain.chain_sql_ubix import get_db_chain def get_tools(llm): global vectorstore with open("./local/vectorstore.pkl", "rb") as f: vectorstore = pickle.load(f) qa_chain = get_kb_chain(llm, vectorstore) local_tool = Tool( name='Query information about Ubix Company', func=qa_chain.run, description='Query information about me and Ubix Company', ) local_tool.return_direct = True db_tool = Tool( name='Query Info about Data', func=get_db_chain(llm).run, description='Query Info about Data in table, Hive or Spark' ) db_tool.return_direct = True tools = [ # local_tool, db_tool , # , get_general_chain() ] return tools # # def get_agent(websocket=None, question_handler=None, stream_handler=None): # tools = get_tools() # manager = AsyncCallbackManager([]) # if True: # tracer = LangChainTracer() # # tracer.load_default_session() # manager.add_handler(tracer) # zero_shot_agent = initialize_agent( # agent="zero-shot-react-description", # tools=tools, # llm=llm, # verbose=True, # # callback_manager=manager, # ) # return zero_shot_agent @lru_cache() def get_agent_conversion(): from langchain.memory import ConversationBufferMemory llm = get_default_llm() tools = get_tools(llm) manager = AsyncCallbackManager([]) memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) from langchain.prompts import MessagesPlaceholder chat_history = MessagesPlaceholder(variable_name="chat_history") agent_chain = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory, callback_manager=manager, agent_kwargs = { "memory_prompts": [chat_history], "input_variables": ["input", "agent_scratchpad", "chat_history"] }) return agent_chain def get_answer(question, verbose=False): zero_shot_agent = get_agent_conversion() answer = zero_shot_agent({"input": question}) if verbose: return answer else: return answer["output"] @lru_cache() def get_default_llm(): n_gpu_layers = 80 # Metal set to 1 is enough. n_batch = 512 # Should be between 1 and n_ctx callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) langchain.llm_cache = InMemoryCache() llm = LlamaCpp( #model_path="/Workspace/yamada/pretrain/LLaMa-7B-GGML/llama-7b.ggmlv3.q4_0.bin", model_path="/Workspace/yamada/pretrain/Llama-2-13B-chat-GGML/llama-2-13b-chat.ggmlv3.q4_0.bin", n_gpu_layers=n_gpu_layers, n_batch=n_batch, n_ctx=2500, f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls callback_manager=callback_manager, verbose=True, cache=True ) return llm @lru_cache() def get_route_llm(): # llm = LlamaCpp( # # model_path="/Workspace/yamada/pretrain/LLaMa-7B-GGML/llama-7b.ggmlv3.q4_0.bin", # model_path="/Workspace/yamada/pretrain/Llama-2-13B-chat-GGML/llama-2-13b-chat.ggmlv3.q4_0.bin", # n_gpu_layers=80, # n_batch=512, # n_ctx=2500, # f16_kv=True, # MUST set to True, otherwise you will run into problem after a couple of calls # callback_manager= CallbackManager([StreamingStdOutCallbackHandler()]), # verbose=True, # # cache=True # ) llm = OpenAI(temperature=0), return llm if __name__ == '__main__': zero_shot_agent = get_agent_conversion() # result = zero_shot_agent({"input": "Who is Ubix?"}) result = zero_shot_agent({"input": "Could you help to count how many rows are there in the table sales_order_item?"}) # result = zero_shot_agent({"input": "Hi, I'm felix"}) # result = zero_shot_agent({"input": "Who am I"}) """ CUDA_VISIBLE_DEVICES=0,1,2,3 PYTHONPATH=. python agent/zero_short.py """
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_din_sql_bone.py
from __future__ import annotations from typing import Any, Dict, List, Optional import pdb from langchain.prompts import PromptTemplate from pydantic import Extra from sqlalchemy.engine import create_engine from trino.sqlalchemy import URL from sqlalchemy import * from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate from ubix.common.llm import get_llm easy_template = """ # Use the the schema links to generate the SQL queries for each of the questions. Q: "Find the buildings which have rooms with capacity more than 50." Schema_links: [classroom.building,classroom.capacity,50] SQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50 Q: "Find the room number of the rooms which can sit 50 to 100 students and their buildings." Schema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100] SQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100 Q: "Give the name of the student in the History department with the most credits." Schema_links: [student.name,student.dept_name,student.tot_cred,History] SQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1 Q: "Find the total budgets of the Marketing or Finance department." Schema_links: [department.budget,department.dept_name,Marketing,Finance] SQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance' Q: "Find the department name of the instructor whose name contains 'Soisalon'." Schema_links: [instructor.dept_name,instructor.name,Soisalon] SQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%' Q: "What is the name of the department with the most credits?" Schema_links: [course.dept_name,course.credits] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1 Q: "How many instructors teach a course in last year?" Schema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022] SQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022 Q: "Find the name of the students and their department names sorted by their total credits in ascending order." Schema_links: [student.name,student.dept_name,student.tot_cred] SQL: SELECT name , dept_name FROM student ORDER BY tot_cred Q: "Find the year which offers the largest number of courses." Schema_links: [SECTION.YEAR,SECTION.*] SQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1 Q: "What are the names and average salaries for departments with average salary higher than 42000?" Schema_links: [instructor.dept_name,instructor.salary,42000] SQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000 Q: "How many rooms in each building have a capacity of over 50?" Schema_links: [classroom.*,classroom.building,classroom.capacity,50] SQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building Q: "Find the names of the top 3 departments that provide the largest amount of courses?" Schema_links: [course.dept_name,course.*] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3 Q: "Find the maximum and average capacity among rooms in each building." Schema_links: [classroom.building,classroom.capacity] SQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building Q: "Find the title of the course that is offered by more than one department." Schema_links: [course.title] SQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1 Q: "show the revenues in last three year?" Schema_links: [product.avenue, 2022, 2019, product.date] SQL: SELECT year(product.date), max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(product.date) Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" schema_links: [{schema_links}] SQL: """ hard_template = """ Q: "Find the title of courses that have two prerequisites?" Schema_links: [course.title,course.course_id = prereq.course_id] SQL: SELECT course.title, prereq.course_id FROM course, prereq WHERE course.course_id = prereq.course_id GROUP BY prereq.course_id HAVING count(*) = 2 Q: "Find the total number of students and total number of instructors for each department." Schema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id] SQL: SELECT count(DISTINCT student.id), count(DISTINCT instructor.id), instructor.dept_name FROM department, student, instructor WHERE department.dept_name = instructor.dept_name and department.dept_name = student.dept_name GROUP BY instructor.dept_name Q: "What are salaries and by employees and cityname employees live in for the past three years?" Schema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR,employee.name,city.city_id=employee.city_id,city.name] SQL: SELECT year(company.YEAR),employee.name,city.name,sum(company.salary) FROM company,employee,city WHERE company.employee_id=employee.employee_id and city.city_id=employee.city_id and company.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(company.YEAR),employee.name,city.name Q: "Find the name of students who took any class in past three years" Schema_links: [student.name,student.id = takes.id,takes.YEAR] SQL: SELECT year(takes.YEAR),DISTINCT student.name FROM student,takes WHERE student.id = takes.id and takes.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(takes.YEAR) Q: "Find the revenues by customer in past three years" Schema_links: [invoices.doctotal,businesspartners.cardname,invoices.docdate,invoices.cardcode=businesspartners.cardcode,cCustomer, businesspartners.cardtype] SQL: SELECT year(invoices.docdate), businesspartners.cardname, sum(invoices.doctotal) FROM invoices, businesspartners WHERE businesspartners.cardtype='cCustomer' and invoices.docdate between '2019-01-01 00:00:00' and '2022-12-31 23:59:59'GROUP BY year(invoices.docdate), businesspartners.cardname Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" Schema_links:{schema_links} SQL: """ schema_linking_prompt = """ Table Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country] Table Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code] Table Candidates, columns = [*,candidate_id,candidate_details] Table Courses, columns = [*,course_id,course_name,course_description,other_details] Table People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password] Table People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to] Table Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance] Table Student_Course_Registrations, columns = [*,student_id,course_id,registration_date] Table Students, columns = [*,student_id,student_details] Foreign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id] Q: "List the id of students who never attends courses?" A: Let’s think step by step. In the question "List the id of students who never attends courses?", we are asked: "id of students" so we need column = [Students.student_id] "never attends courses" so we need column = [Student_Course_Attendance.student_id] Based on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id]. Based on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are: Schema_links: [Students.student_id = Student_Course_Attendance.student_id] Table invoices, columns = [*,docdate,doctotal,docnum,cardcode] Table items, columns = [*,itemname,itemcode] Table productionorders, columns = [*,itemno,documentnumber] Table businesspartners, columns = [*,cardname,cardcode] Foreign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode] Q: "List the revenue by product for past year" A: Let�~@~Ys think step by step. In the question"List the revenue by product for past year, we are asked: "the revenue" so we need column = [invoices.doctotal] "by product" so we need column = [items.itemname, productionorders.*] "for past year" so we need column = [invoices.docdate] Based on the columns and tables, we need these Foreign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode] Based on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are: Schema_links: [invoices.doctotal,items.itemname,invoices.docdate,invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,1] Table invoices, columns = [*,docdate,doctotal,docnum,cardcode] Table items, columns = [*,itemname,itemcode] Table productionorders, columns = [*,itemno,documentnumber] Table businesspartners, columns = [*,cardname,cardcode,cardtype] Foreign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode] Q: "List the revenue by customer for past year" A: Let�~@~Ys think step by step. In the question"List the revenue by customer for past year", we are asked: "the revenue" so we need column = [invoices.doctotal] "by customer" so we need column = [businesspartners.cardcode,businesspartners.cardname] Based on the columns and tables, we need these Foreign_keys = [invoices.cardcode=businesspartners.cardcode] Based on the tables, columns, and Foreign_keys, The set of possible cell values are = [cCustomer]. So the Schema_links are: Schema_links: [invoices.doctotal,businesspartners.cardname,businesspartners.cardtype,invoices.cardcode=businesspartners.cardcode,cCustomer] """ PROMPT = PromptTemplate( input_variables=["input", "schema_links"], template=easy_template, ) def format(sql): if "date" in sql: result = sql.replace("\'20", "TIMESTAMP \'20").replace("\"20", "TIMESTAMP \"20") return result else: return sql def hive_search(sql): hive_host = "trino" port = 8080 user_name = "hive" catalog="hive" #hive_database = "65057500bed4c2ac869fe964" hive_database = "654a464f1dd821018bd47cd5" #hive_database = "65487027ce6b72312eff28a2" engine = create_engine( URL( host=hive_host, port=port, user=user_name, catalog=catalog, schema=hive_database, ), ) with engine.connect() as con: sql = format(sql) #sql = "select count(*) from Invoice_Header;" #print(sql) result_t = con.execute(text(sql)) result = result_t.fetchall() return result class DIN_Chain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables[:1] @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain #pdb.set_trace() from datetime import datetime start = datetime.now() schema_links_prompt = schema_linking_prompt_maker(inputs.get("input")) schema_links = self.llm(schema_links_prompt) schema_links = schema_links.split("\n\n")[0].split("Schema_links: ")[1] end = datetime.now() #print("schema cost:", end - start) #schema_links, is_hard = get_schema_links(inputs.get("input")) #schema_links = "[invoice_header.totalnetamount,invoice_header.creationdatetime]" inputs["schema_links"] = schema_links if "by" in inputs.get("input"): self.prompt.template = hard_template else: self.prompt.template = easy_template start = datetime.now() prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) #print(f'Original response:{response}') text = response.generations[0][0].text #pdb.set_trace() #print(f'Final Text:{text}') result_ = text.split("\n\n")[0] result_ = result_.replace("\n", " ") end = datetime.now() #print("llm cost:", end - start) print(f'🔴Final SQL:{result_}\n=====') final = hive_search(result_) key_list = [] for item in result_.split(" FROM")[0].split(","): item = item.replace(" ", "").replace(")", "") item = item.split(".") key_list.append(item[1]) res = [] for f_item in final: dct_item = {} try: for index, e_item in enumerate(f_item): dct_item[key_list[index]] = str(f_item[index]) except: pass res.append(dct_item) dct_final = res dct = {} dct["sql"] = result_ dct["answer"] = dct_final #print("dct", dct) print("============================") # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key:dct} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: #print(f'DummyChain:{inputs}') # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain" def schema_linking_prompt_maker(test_sample_text): instruction = "# Find the schema_links for generating SQL queries for each question based on the database schema and Foreign keys.\n" fields = """ Table invoices, columns = [docdate,doctotal,docnum] Table items, columns = [itemname,itemcode] Table productionorders, columns = [itemno,documentnumber] """ foreign_keys = """ [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode] """ global schema_linking_prompt prompt = instruction + schema_linking_prompt + fields +foreign_keys+ 'Q: "' + test_sample_text + """"\nA: Let’s think step by step.""" return prompt def get_din_chain(llm): chain = DIN_Chain(llm=llm, prompt=PROMPT) return chain if __name__ == "__main__": llm = get_llm() chain = get_din_chain(llm) #query = "What are our revenues for the past 3 years" query = "what are our revenues by product for the past 13 years" #query = "what are our revenues by customer for the past 3 years" #query = "Can you show me our monthly income statements for the last 12 months?" result = chain.run(query) print(result) """ PYTHONPATH=. LLM_TYPE=din python ubix/chain/chain_din_sql.py """
[ "What is the name of the department with the most credits?", "Find the title of the course that is offered by more than one department.", "Spring", "\n# Use the the schema links to generate the SQL queries for each of the questions.\nQ: \"Find the buildings which have rooms with capacity more than 50.\"\nSchema_links: [classroom.building,classroom.capacity,50]\nSQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50\n\nQ: \"Find the room number of the rooms which can sit 50 to 100 students and their buildings.\"\nSchema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100]\nSQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100\n\nQ: \"Give the name of the student in the History department with the most credits.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred,History]\nSQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1\n\nQ: \"Find the total budgets of the Marketing or Finance department.\"\nSchema_links: [department.budget,department.dept_name,Marketing,Finance]\nSQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance'\n\nQ: \"Find the department name of the instructor whose name contains 'Soisalon'.\"\nSchema_links: [instructor.dept_name,instructor.name,Soisalon]\nSQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%'\n\nQ: \"What is the name of the department with the most credits?\"\nSchema_links: [course.dept_name,course.credits]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1\n\nQ: \"How many instructors teach a course in last year?\"\nSchema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022]\nSQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022\n\nQ: \"Find the name of the students and their department names sorted by their total credits in ascending order.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred]\nSQL: SELECT name , dept_name FROM student ORDER BY tot_cred\n\nQ: \"Find the year which offers the largest number of courses.\"\nSchema_links: [SECTION.YEAR,SECTION.*]\nSQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1\n\nQ: \"What are the names and average salaries for departments with average salary higher than 42000?\"\nSchema_links: [instructor.dept_name,instructor.salary,42000]\nSQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000\n\nQ: \"How many rooms in each building have a capacity of over 50?\"\nSchema_links: [classroom.*,classroom.building,classroom.capacity,50]\nSQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building\n\nQ: \"Find the names of the top 3 departments that provide the largest amount of courses?\"\nSchema_links: [course.dept_name,course.*]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3\n\nQ: \"Find the maximum and average capacity among rooms in each building.\"\nSchema_links: [classroom.building,classroom.capacity]\nSQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building\n\nQ: \"Find the title of the course that is offered by more than one department.\"\nSchema_links: [course.title]\nSQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1\n\nQ: \"show the revenues in last three year?\"\nSchema_links: [product.avenue, 2022, 2019, product.date]\nSQL: SELECT year(product.date), max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(product.date)\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nschema_links: [{schema_links}]\nSQL:\n", "What are the names and average salaries for departments with average salary higher than 42000?", "show the revenues in last three year?", "Find the year which offers the largest number of courses.", "Finance", "Find the total budgets of the Marketing or Finance department.", "Find the buildings which have rooms with capacity more than 50.", "Give the name of the student in the History department with the most credits.", "Find the room number of the rooms which can sit 50 to 100 students and their buildings.", "\nTable Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country]\nTable Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code]\nTable Candidates, columns = [*,candidate_id,candidate_details]\nTable Courses, columns = [*,course_id,course_name,course_description,other_details]\nTable People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password]\nTable People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to]\nTable Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance]\nTable Student_Course_Registrations, columns = [*,student_id,course_id,registration_date]\nTable Students, columns = [*,student_id,student_details]\nForeign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id]\nQ: \"List the id of students who never attends courses?\"\nA: Let’s think step by step. In the question \"List the id of students who never attends courses?\", we are asked:\n\"id of students\" so we need column = [Students.student_id]\n\"never attends courses\" so we need column = [Student_Course_Attendance.student_id]\nBased on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are:\nSchema_links: [Students.student_id = Student_Course_Attendance.student_id]\n\nTable invoices, columns = [*,docdate,doctotal,docnum,cardcode]\nTable items, columns = [*,itemname,itemcode]\nTable productionorders, columns = [*,itemno,documentnumber]\nTable businesspartners, columns = [*,cardname,cardcode]\nForeign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode]\nQ: \"List the revenue by product for past year\"\nA: Let�~@~Ys think step by step. In the question\"List the revenue by product for past year, we are asked:\n\"the revenue\" so we need column = [invoices.doctotal]\n\"by product\" so we need column = [items.itemname, productionorders.*]\n\"for past year\" so we need column = [invoices.docdate]\nBased on the columns and tables, we need these Foreign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode]\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are:\nSchema_links: [invoices.doctotal,items.itemname,invoices.docdate,invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,1]\n\nTable invoices, columns = [*,docdate,doctotal,docnum,cardcode]\nTable items, columns = [*,itemname,itemcode]\nTable productionorders, columns = [*,itemno,documentnumber]\nTable businesspartners, columns = [*,cardname,cardcode,cardtype]\nForeign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode]\nQ: \"List the revenue by customer for past year\"\nA: Let�~@~Ys think step by step. In the question\"List the revenue by customer for past year\", we are asked:\n\"the revenue\" so we need column = [invoices.doctotal]\n\"by customer\" so we need column = [businesspartners.cardcode,businesspartners.cardname]\nBased on the columns and tables, we need these Foreign_keys = [invoices.cardcode=businesspartners.cardcode]\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [cCustomer]. So the Schema_links are:\nSchema_links: [invoices.doctotal,businesspartners.cardname,businesspartners.cardtype,invoices.cardcode=businesspartners.cardcode,cCustomer]\n\n", "%Soisalon%", "input", "schema_links", "\nQ: \"Find the title of courses that have two prerequisites?\"\nSchema_links: [course.title,course.course_id = prereq.course_id]\nSQL: SELECT course.title, prereq.course_id FROM course, prereq WHERE course.course_id = prereq.course_id GROUP BY prereq.course_id HAVING count(*) = 2\n\nQ: \"Find the total number of students and total number of instructors for each department.\"\nSchema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id]\nSQL: SELECT count(DISTINCT student.id), count(DISTINCT instructor.id), instructor.dept_name FROM department, student, instructor WHERE department.dept_name = instructor.dept_name and department.dept_name = student.dept_name GROUP BY instructor.dept_name\n\nQ: \"What are salaries and by employees and cityname employees live in for the past three years?\"\nSchema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR,employee.name,city.city_id=employee.city_id,city.name]\nSQL: SELECT year(company.YEAR),employee.name,city.name,sum(company.salary) FROM company,employee,city WHERE company.employee_id=employee.employee_id and city.city_id=employee.city_id and company.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(company.YEAR),employee.name,city.name\n\nQ: \"Find the name of students who took any class in past three years\"\nSchema_links: [student.name,student.id = takes.id,takes.YEAR]\nSQL: SELECT year(takes.YEAR),DISTINCT student.name FROM student,takes WHERE student.id = takes.id and takes.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(takes.YEAR)\n\nQ: \"Find the revenues by customer in past three years\"\nSchema_links: [invoices.doctotal,businesspartners.cardname,invoices.docdate,invoices.cardcode=businesspartners.cardcode,cCustomer, businesspartners.cardtype]\nSQL: SELECT year(invoices.docdate), businesspartners.cardname, sum(invoices.doctotal) FROM invoices, businesspartners WHERE businesspartners.cardtype='cCustomer' and invoices.docdate between '2019-01-01 00:00:00' and '2022-12-31 23:59:59'GROUP BY year(invoices.docdate), businesspartners.cardname\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nSchema_links:{schema_links}\nSQL:\n", "Find the department name of the instructor whose name contains 'Soisalon'.", "How many rooms in each building have a capacity of over 50?", "PLACEHOLDER", "2022-12-31 23:59:59", "How many instructors teach a course in last year?", "Marketing", "Find the maximum and average capacity among rooms in each building.", "{input}", "Find the names of the top 3 departments that provide the largest amount of courses?", "# Find the schema_links for generating SQL queries for each question based on the database schema and Foreign keys.\n\nTable Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country]\nTable Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code]\nTable Candidates, columns = [*,candidate_id,candidate_details]\nTable Courses, columns = [*,course_id,course_name,course_description,other_details]\nTable People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password]\nTable People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to]\nTable Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance]\nTable Student_Course_Registrations, columns = [*,student_id,course_id,registration_date]\nTable Students, columns = [*,student_id,student_details]\nForeign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id]\nQ: \"List the id of students who never attends courses?\"\nA: Let’s think step by step. In the question \"List the id of students who never attends courses?\", we are asked:\n\"id of students\" so we need column = [Students.student_id]\n\"never attends courses\" so we need column = [Student_Course_Attendance.student_id]\nBased on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are:\nSchema_links: [Students.student_id = Student_Course_Attendance.student_id]\n\nTable invoices, columns = [*,docdate,doctotal,docnum,cardcode]\nTable items, columns = [*,itemname,itemcode]\nTable productionorders, columns = [*,itemno,documentnumber]\nTable businesspartners, columns = [*,cardname,cardcode]\nForeign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode]\nQ: \"List the revenue by product for past year\"\nA: Let�~@~Ys think step by step. In the question\"List the revenue by product for past year, we are asked:\n\"the revenue\" so we need column = [invoices.doctotal]\n\"by product\" so we need column = [items.itemname, productionorders.*]\n\"for past year\" so we need column = [invoices.docdate]\nBased on the columns and tables, we need these Foreign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode]\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are:\nSchema_links: [invoices.doctotal,items.itemname,invoices.docdate,invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,1]\n\nTable invoices, columns = [*,docdate,doctotal,docnum,cardcode]\nTable items, columns = [*,itemname,itemcode]\nTable productionorders, columns = [*,itemno,documentnumber]\nTable businesspartners, columns = [*,cardname,cardcode,cardtype]\nForeign_keys = [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode,invoices.cardcode=businesspartners.cardcode]\nQ: \"List the revenue by customer for past year\"\nA: Let�~@~Ys think step by step. In the question\"List the revenue by customer for past year\", we are asked:\n\"the revenue\" so we need column = [invoices.doctotal]\n\"by customer\" so we need column = [businesspartners.cardcode,businesspartners.cardname]\nBased on the columns and tables, we need these Foreign_keys = [invoices.cardcode=businesspartners.cardcode]\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [cCustomer]. So the Schema_links are:\nSchema_links: [invoices.doctotal,businesspartners.cardname,businesspartners.cardtype,invoices.cardcode=businesspartners.cardcode,cCustomer]\n\n\n Table invoices, columns = [docdate,doctotal,docnum]\n Table items, columns = [itemname,itemcode]\n Table productionorders, columns = [itemno,documentnumber]\n \n [invoices.docnum=productionorders.documentnumber,productionorders.itemno=items.itemcode]\n Q: \"PLACEHOLDER\"\nA: Let’s think step by step.", "Find the name of the students and their department names sorted by their total credits in ascending order.", "2019-01-01 00:00:00" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~DummyChain.py
from __future__ import annotations from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate class DummyChain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: print(f'DummyChain:{inputs}') # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain"
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
agent~chain_general_ubix.py
from langchain import PromptTemplate, LLMChain from langchain.tools import Tool def get_general_chain(llm): prompt = PromptTemplate( input_variables=["question"], template="""{question}""" ) search_chain = LLMChain(llm=llm, prompt=prompt) search_tool = Tool( name='General Question', func=search_chain.run, description='General Question' ) search_tool.return_direct = True return search_tool
[ "question", "{question}" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_sql_ubix.py
from datetime import datetime from sqlalchemy.engine import create_engine from trino.sqlalchemy import URL from ubix.chain.sql.sql_base import SQLDatabaseChainEx, SQLDatabaseEx from ubix.common.llm import llm, get_llm from ubix.common.log_basic import logging try: from langchain import SQLDatabaseChain except Exception as e: from langchain_experimental.sql import SQLDatabaseChain def get_db_chain(llm): hive_host = "trino" port = 8080 user_name = "hive" catalog="hive" include_tables = ["salesopportunities"] hive_database = "65057500bed4c2ac869fe964" engine = create_engine( URL( host=hive_host, port=port, user=user_name, catalog=catalog, schema=hive_database, ), ) sql_db = SQLDatabaseEx(engine, schema=hive_database, include_tables=include_tables) llm = get_llm() db_chain = SQLDatabaseChainEx.from_llm(llm=llm, db=sql_db, verbose=True) return db_chain if __name__ == "__main__": print(datetime.now()) start = datetime.now() agent = get_db_chain(llm) """ query = "how many records are there in this table?" print(datetime.now()) agent.run(query) """ query = "what is the maximum total in this table?" answer = agent.run(query) print(datetime.now()) """ query = "What is the maximum total in the city Novi" agent.run(query) print(datetime.now()) """ end = datetime.now() duration = (end-start).total_seconds() logging.info("🔴 answer:\n" + answer) logging.info("⏰ " + f"Query: cost:{duration:.0f} sec seconds") """ RAY_memory_monitor_refresh_ms=0 CUDA_VISIBLE_DEVICES=0,1 PYTHONPATH=. LLM_TYPE=vllm python ubix/chain/chain_sql_ubix.py PYTHONPATH=. LLM_TYPE=din python ubix/chain/chain_sql_ubix.py PYTHONPATH=. LLM_TYPE=tgi python ubix/chain/chain_sql_ubix.py """
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~common~logHander.py
from typing import Any from langchain.callbacks.base import BaseCallbackHandler class LogHandler(BaseCallbackHandler): def __init__(self, name): self.name = name or "LogHandler" def on_text( self, text: str, **kwargs: Any, ) -> Any: print(f"======== Here is the {self.name} info Begin=========") print(text) print(f"======== Here is the {self.name} info End=========")
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
main_api.py
from ubix.common.api_status import APIStatus from ubix.common.log_basic import logging import os import time import uuid from datetime import datetime from addict import Dict from flask import Flask, request, jsonify, Response from langchain import OpenAI from threading import Lock from route.router import router_chain, llm, get_route_meta from ubix.common.answer import get_answer from ubix.common.conversation_manage import get_or_create_conversion, update_conversation, get_conversation_list, \ get_conversation_by_id, save_conversation import json config = { "DEBUG": True, # some Flask specific configs } app = Flask(__name__) # tell Flask to use the above defined config app.config.from_mapping(config) conversion_storage = {} lock = Lock() route_meta = get_route_meta() @app.route("/") def hello(): return "hello" @app.route("/get_llm_api_status", methods=['GET']) def get_llm_api_status(): enable_llm = request.args.get('enable_llm') if enable_llm: enable_llm = enable_llm.lower() == 'true' else: enable_llm = False res: Dict = APIStatus().get_api_status(enable_llm=enable_llm) return Response(json.dumps(res, indent=4), mimetype='application/json') @app.route("/get_conversation_list", methods=['GET']) def _get_conversation_list(): user_id = request.args.get('user_id') conversation_list = get_conversation_list(user_id) return conversation_list @app.route("/get_conversation", methods=['GET']) def _get_conversation(): id = request.args.get('id') conversation = get_conversation_by_id(id) return conversation @app.route("/update_conversation", methods=['POST']) def _update_conversation(): request_data = Dict(request.json).data logging.info(request.json) logging.info(request.headers) args = { "_id": request_data.conversation_id, "user_id": request.headers.get("User-ID", "UNKNOWN"), "conversation_id": request_data.conversation_id, } if "query_type" in request_data: args["query_type"] = request_data.query_type if "conversation_name" in request_data: args["conversation_name"] = request_data.conversation_name return update_conversation(args) @app.route("/chat/v2", methods=['POST']) def get_bot_response_dummpy(): start = datetime.now() request_data = Dict(request.json).data question = request_data.question logging.info(f"question:{question}, request data:{request_data}, header:{request.headers}") with lock: route_name, answer = get_answer(question, history=None, query_type=request_data.query_type) sql = None #print(f"answer type:{type(answer)}, route_name:{route_name}, {list(answer.keys())}") widgets = None if route_name in ["query", "download"]: # answer = Dict(json.loads(answer)) sql = answer.get("sql") answer = answer.get("answer") widgets = "table" end = datetime.now() duration = (end-start).total_seconds() logging.info(f"Try to get the conversation") download_type = "download" conversion = get_or_create_conversion(request_data, request.headers) logging.info(f"Try to save the conversation") current_qa = {"id": uuid.uuid4().hex[:24], "question": question, "answer": answer, "related_sql": sql, "query_type": request_data.query_type, "route": route_name, "start_time": start.strftime('%Y-%m-%d %H:%M:%S'), "duration": duration, "host_name": os.environ.get("HOSTNAME", "UNKNOWN"), "llm_type": os.getenv("LLM_TYPE", "UNKNOWN"), "widget_type": widgets, "download_type": download_type, } conversion.conversation_list.append(current_qa) if route_name != "error": save_conversation(conversion) logging.info("Conversation save successfully") qa_response = conversion conversion.pop("_id") conversion.pop("conversation_list") current_qa["conversation_id"] = qa_response["conversation_id"] qa_response["qa_data"] = current_qa return qa_response @app.route("/timeout_test") def timeout_test(): time.sleep(150) return f"delay 150 seconds" def get_route_name(question): stop = None if isinstance(router_chain.llm, OpenAI) else "\n" route_name_original = router_chain.run(input=str(question), stop=stop) route_name = route_name_original.strip().split(':')[-1].strip() route_name = route_name if route_name in route_meta else "other" logging.info(f"route_name:{route_name_original}=>{route_name}") return route_name if __name__ == '__main__': app.run(debug=True, host="0.0.0.0") """" CUDA_VISIBLE_DEVICES=0 LLM_TYPE=vllm nohup python -u main_api.py >api.log 2>&1 & CUDA_VISIBLE_DEVICES=0 LLM_TYPE=gglm nohup python -u main_api.py >api.log 2>&1 & CUDA_VISIBLE_DEVICES=0 LLM_TYPE=tgi nohup python -u main_api.py >api.log 2>&1 & curl "http://colossal-ai.data-tooling.svc.cluster.local:5000/chat/v2" \ -H 'User-ID: user_123' \ -H 'Account-ID: acct_12345' \ -H 'Content-Type: application/json' \ --data-raw '{"data":{"query_type":"query", "question":"How many records in this table", "conversation_id":"8f187c01601c" }}' \ --compressed \ --insecure | jq curl 'https://colossal-ai.home-dev.ubix.io/chat/v2' \ -H 'User-ID: user_123' \ -H 'Account-ID: acct_12345' \ -H 'Content-Type: application/json' \ --data-raw '{"data":{"query_type":"download", "question":"list the data with cardcode C40000 in this table", "conversation_id":"8f187c01601c" }}' \ --compressed \ --insecure | jq curl 'https://colossal-ai.home-dev.ubix.io/update_conversation' \ -H 'User-ID: user_123' \ -H 'Account-ID: acct_12345' \ -H 'Content-Type: application/json' \ --data-raw '{"data":{"conversation_name":"hello_123", "conversation_id":"8f187c01601c" }}' \ --compressed \ --insecure | jq curl 'http://colossal-ai.data-tooling.svc.cluster.local:5000/get_conversation_list?user_id=user_123' curl 'http://colossal-ai.data-tooling.svc.cluster.local:5000/get_llm_api_status?enable_llm=false' curl 'http://colossal-ai.data-tooling.svc.cluster.local:5000/get_llm_api_status?enable_llm=true' curl 'http://colossal-ai.data-tooling.svc.cluster.local:5000/get_conversation?id=8f187c01601c' curl -X POST -d "question=How many records in this table" https://colossal-ai.home-dev.ubix.io/chat curl --connect-timeout 500 --location --request POST "https://colossal-ai.home-dev.ubix.io/chat" \ -d "question=What is the maximum total in this table?" curl --connect-timeout 500 --location --request POST "https://colossal-ai.home-dev.ubix.io/chat" \ -d "question=What is black body radiation?" curl --connect-timeout 500 --location --request POST "https://colossal-ai.home-dev.ubix.io/chat" \ -d "question=Hello, I'm Felix" curl --connect-timeout 500 --location --request POST "https://colossal-ai.home-dev.ubix.io/chat" \ -d "question=Hello, I'm Felix" curl --connect-timeout 500 --location --request POST "https://colossal-ai.home-dev.ubix.io/chat_dummpy" \ -d "question=hello" curl --connect-timeout 500 --location --request POST "http://localhost:5000/chat" \ -d "question=Hello, I'm Felix" time curl https://colossal-ai.home-dev.ubix.io/timeout_test time curl http://colossal-ai/timeout_test """
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~routeSample_v4.py
from datetime import datetime from langchain import PromptTemplate, LLMChain from tqdm import tqdm from ubix.common.llm import get_llm prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task, for question about\ data or table, classify them into Category '''query'''. For other type of questions, \ classify them into Category '''other'''. Your answer must be only one word, \ Here are a few of examples: \ User: How many records in the table? \ Assistant: query \ User: What's the max number in table \ Assistant: query \ User: What's the sells amount in this month. \ Assistant: query \ User: who are you? \ Assistant: other \ User: what is your name? \ Assistant: other \ User:{input} Assistant: """ ) search_chain = LLMChain(llm=get_llm(), prompt=prompt) for _ in tqdm(range(1)): question_list = [ "Hello, I'm Felix", # "Who are you?", # "How many records in this table", "What is the maximum total in this table?", "What is black body radiation?", "What is the definition of classification?", "help to create a modelspace", "Sum the total in this table" ] for question in question_list: start = datetime.now() answer = search_chain.run(question) end = datetime.now() duration_route = (end-start).total_seconds() duration = (end-start).total_seconds() print(f">>>>>"*10 + f"\nEnd ask about question {question}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ CUDA_VISIBLE_DEVICES=3 python test/routeSample.py """
[ "input", "\nYou are currently doing a classification task, for question aboutdata or table, classify them into Category '''query'''. For other type of questions, classify them into Category '''other'''. Your answer must be only one word, \nHere are a few of examples: \nUser: How many records in the table? Assistant: query \nUser: What's the max number in table Assistant: query \nUser: What's the sells amount in this month. Assistant: query \nUser: who are you? Assistant: other \nUser: what is your name? Assistant: other \nUser:{input}\nAssistant: " ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_route.py
from datetime import datetime from langchain import PromptTemplate, LLMChain from tqdm import tqdm from ubix.common.llm import llm def get_route_chain(llm): prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task. Given a raw text input to a language model select the class best suited for \ the input. You will be given the names of the available class and a description of \ what the prompt is best suited for. << FORMATTING >> Return the class name directly, the output should only include one word. REMEMBER: "class" MUST be one of the candidate names specified below OR \ it can be "other" if the input is not well suited for any of the candidate prompts. << CLASS DEFINITION >> query: The request to query the table in database, only for table. Here are some key words: maximum, min, max, avg, table, sum up, revenue, total and so on. api: The request to create something, or query information about ubix. Here are some key words: workspace, function, modelspace, action. other: The requests apart from above two situations belongs to this category. << EXAMPLE >> question: How many records in the table? answer: query question: What's the maximum number in table? answer: query question: What's the revenue in last year? answer: query question: Sum up the revenue for last three years answer: query question: who are you? answer: other question: what is your name? answer: other question: What is black body radiation? answer: other question: help to create a modelspace? answer: api question: How many modelspaces are created? answer: api question: What is the differences between action and function? answer: api << INPUT >> {input} << OUTPUT (the output should only include one word.) >> """ ) route_chain = LLMChain(llm=llm, prompt=prompt) return route_chain if __name__ == '__main__': route_chain = get_route_chain(llm) print(2) for _ in tqdm(range(1)): question_list = [ "hello!", "Hello", "Hello, I'm Felix", "Who are you?", "How many records in this table", "What is the maximum total in this table?", "What is black body radiation?", "How many actions are created", "How many workspaces are created", ] for question in question_list: start = datetime.now() answer = route_chain.run(input=question, stop=["\n"]) end = datetime.now() duration_route = (end-start).total_seconds() duration = (end-start).total_seconds() print(f"⏰ " + f"End ask about question {question}, cost:{duration} sec, answer:{answer}\n" + "<<<<"*10) """ CUDA_VISIBLE_DEVICES=0,1 LLM_TYPE=vllm python ubix/chain/chain_route.py CUDA_VISIBLE_DEVICES=0,1 LLM_TYPE=gglm python ubix/chain/chain_route.py CUDA_VISIBLE_DEVICES=0,1 LLM_TYPE=tgi python ubix/chain/chain_route.py """
[ "input", "\nYou are currently doing a classification task. Given a raw text input to a language model select the class best suited for the input. You will be given the names of the available class and a description of what the prompt is best suited for.\n\n<< FORMATTING >>\nReturn the class name directly, the output should only include one word.\n\nREMEMBER: \"class\" MUST be one of the candidate names specified below OR it can be \"other\" if the input is not well suited for any of the candidate prompts.\n\n\n<< CLASS DEFINITION >>\nquery: The request to query the table in database, only for table. Here are some key words: maximum, min, max, avg, table, sum up, revenue, total and so on.\napi: The request to create something, or query information about ubix. Here are some key words: workspace, function, modelspace, action.\nother: The requests apart from above two situations belongs to this category.\n\n<< EXAMPLE >>\nquestion: How many records in the table?\nanswer: query\nquestion: What's the maximum number in table?\nanswer: query\nquestion: What's the revenue in last year?\nanswer: query\nquestion: Sum up the revenue for last three years\nanswer: query\nquestion: who are you?\nanswer: other\nquestion: what is your name?\nanswer: other\nquestion: What is black body radiation?\nanswer: other\nquestion: help to create a modelspace?\nanswer: api\nquestion: How many modelspaces are created?\nanswer: api\nquestion: What is the differences between action and function?\nanswer: api\n<< INPUT >>\n{input}\n\n<< OUTPUT (the output should only include one word.) >>\n " ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_bot_ubix.py
from datetime import datetime from functools import lru_cache from typing import Any import re import langchain import torch from langchain.cache import InMemoryCache from langchain.callbacks import StreamingStdOutCallbackHandler from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.manager import CallbackManager from langchain.schema import LLMResult from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain from langchain import PromptTemplate, LLMChain from pydantic import Extra from sqlalchemy import * from sqlalchemy.engine import create_engine from sqlalchemy.schema import * from langchain import LlamaCpp, OpenAI from trino.sqlalchemy import URL from ubix.common.llm import get_llm try: from langchain import SQLDatabaseChain except Exception as e: from langchain_experimental.sql import SQLDatabaseChain class SQLEnhancementHandler(BaseCallbackHandler): def on_llm_end( self, response: LLMResult, **kwargs: Any, ) -> Any: sql_cmd = response.generations[0][0].text response.generations[0][0].text = re.sub(r';$', '', sql_cmd) def create_table(table_columns, include_tables, query): """ create a custom table to reduce the reduclant column table_columns: origninal table columns include_tables: table name query: use query to choose the most relevant column """ table_name = include_tables[0] custom_table_info = {} prefix = "CREATE TABLE " + table_name + " (" query_list = query.split(" ") mid = "" for item in table_columns: # mid = ",".join([item for item in query_list if item in query_list]) if item in query_list: mid += item + "," last = ")" custom_table_info[table_name] = prefix + mid + last return custom_table_info def check_query_or_other(query): prompt = PromptTemplate( input_variables=["input"], template=""" You are currently doing a classification task, for question about\ data or table, classify them into Category '''query'''. For other type of questions, \ classify them into Category '''other'''. Your answer must be only one word, \ Here are a few of examples: \ User: How many records in the table? \ Assistant: query \ User: What's the max number in table \ Assistant: query \ User: What's the sells amount in this month. \ Assistant: query \ User: What's the average product amount in last year. \ Assistant: query \ User: who are you? \ Assistant: other \ User: what is your name? \ Assistant: other \ User:{input} Assistant: """ ) search_chain = LLMChain(llm=llm, prompt=prompt) label = search_chain.run(query) result = label.split("\n")[0] return result def get_db_chain(llm, query, database): import langchain as lc include_tables = [database] hive_host = "trino" port = 8080 user_name = "hive" catalog="hive" hive_database = "63bd509c8cb02db7e453ad27" engine = create_engine( URL( host=hive_host, port=port, user=user_name, catalog=catalog, schema=hive_database, ), ) # query = "what is the maximum total in this table?" connetion = engine.connect() metadata = MetaData() table = Table(include_tables[0], metadata, autoload=True, autoload_with=engine) table_columns = table.columns.keys() custom_table_info = create_table(table_columns, include_tables, query) con_custom = lc.SQLDatabase(engine, include_tables=include_tables, custom_table_info=custom_table_info) llm.callbacks=[SQLEnhancementHandler()] db_chain = SQLDatabaseChain.from_llm(llm=llm, db=con_custom, verbose=True) return db_chain if __name__ == "__main__": llm = get_llm() config = { "total": "sales_order_item", } question_round1 = "Hello, I'm Felix" question_round2 = "what is the maximum total in this table?" question_round3 = "what is the maximum price_total in last year?" question_round_list = [question_round1, question_round2, question_round3] memory=ConversationBufferMemory() conversation = ConversationChain( llm=llm, verbose=True, memory=memory ) for question_round in question_round_list: flag = check_query_or_other(question_round) if "query" in flag: no_database = False database = "" for item in question_round.split(" "): if item in config: no_database = True database = config[item] if not no_database: print("choose suitable table") else: agent = get_db_chain(llm, question_round, database) round = agent.run(question_round) else: round = conversation.predict(input=question_round) print("round", round) """ CUDA_VISIBLE_DEVICES=3 PYTHONPATH=. python ubix/chain/chain_sql_ubix.py """
[ "\n You are currently doing a classification task, for question about data or table, classify them into Category '''query'''. For other type of questions, classify them into Category '''other'''. Your answer must be only one word, \n Here are a few of examples: \n User: How many records in the table? Assistant: query \n User: What's the max number in table Assistant: query \n User: What's the sells amount in this month. Assistant: query \n User: What's the average product amount in last year. Assistant: query \n User: who are you? Assistant: other \n User: what is your name? Assistant: other \n User:{input}\n Assistant: ", "input" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~common~answer.py
from datetime import datetime from langchain import OpenAI from tqdm import tqdm from requests.exceptions import ConnectionError from ubix.common.log_basic import logging #from route.router import route_meta, default_chain, router_chain from route.router import default_chain, router_chain import route.router as router from langchain.utils.math import cosine_similarity import os import re import pickle import pdb import numpy as np import requests def get_route_name(question): stop = None if isinstance(router_chain.llm, OpenAI) else ["\n"] route_name_original = router_chain.run(input=str(question), stop=stop) route_name = route_name_original.strip().split(':')[-1].strip() #route_name = route_name if route_name in route_meta else "other" print(f"route_name:{route_name_original}=>{route_name}") return route_name def get_answer(question: str, history, query_type="auto"): start_route = datetime.now() answer = "" try: start = datetime.now() route_meta = router.get_route_meta() route_name = get_route_name(question) if query_type == "auto" else query_type logging.info("***********************") logging.info(f"step one: choose the proper route {route_name}, current route:{list(route_meta.keys())}") duration_route = (start-start_route).total_seconds() logging.info(f'>>>: Begin ask <{route_name}> about question: <{question}>, route cost:{duration_route} sec') if route_name in route_meta: if "query" in route_name: chain_list = route_meta[route_name] answer = {} sql_dct = {} answer_dct = {} answer_chain_sap = chain_list[0].run(question) sql_dct["sap"] = answer_chain_sap["sql"] answer_dct["sap"] = answer_chain_sap["answer"] answer_chain_bone = chain_list[1].run(question) sql_dct["bone"] = answer_chain_bone["sql"] answer_dct["bone"] = answer_chain_bone["answer"] answer["sql"] = sql_dct answer["answer"] = answer_dct else: answer = route_meta[route_name].run(question) if "other" in route_name: try: if answer.startswith("?\n"): answer = answer.split("\n")[1] except: pass else: answer = default_chain.run(question) except ConnectionError as ex: answer = f"❌:Connection issue:{type(ex)},{str(ex)}" route_name = "error" #print("step three: the final result is", answer, "\n") end = datetime.now() duration = (end-start).total_seconds() #logging.info(f'🔴: End ask route:<{route_name}> about question <{question}>, cost:{duration} sec, answer: {answer}') #logging.info("⏰" + f" Route:{route_name} cost:{duration_route:.0f} seconds, Query: cost:{duration:.0f}sec seconds") return route_name, answer if __name__ == '__main__': import os for _ in tqdm(range(1), desc="Answer testing"): if os.environ.get("LLM_TYPE", None) == "din": question_list = [ ("What is machine learning", "auto"), ("what are our revenues by product for the past 13 years", "auto"), ] for question, query_type in question_list: print("question: ", question) get_answer(question, None, query_type=query_type) else: question_list = [ ("What is black body radiation", "auto"), ("what is the maximum total in this table?", "query"), ("how many records are there in this table?", "query"), ] for question, query_type in question_list: get_answer(question, None, query_type=query_type) """ CUDA_VISIBLE_DEVICES=1 PYTHONPATH=. LLM_TYPE=gglm python ubix/common/answer.py RAY_memory_monitor_refresh_ms=0 CUDA_VISIBLE_DEVICES=0,1 \ PYTHONPATH=. LLM_TYPE=vllm python ubix/common/answer.py PYTHONPATH=. LLM_TYPE=gglm python ubix/common/answer.py ✅ PYTHONPATH=. LLM_TYPE=tgi python -u ubix/common/answer.py ✅ PYTHONPATH=. LLM_TYPE=din python -u ubix/common/answer.py """
[]
2024-01-10
wofeichangaiwoai/din_sql_llm
ubix~chain~chain_din_sql_sap.py
from __future__ import annotations import datetime from typing import Any, Dict, List, Optional import pdb from langchain.prompts import PromptTemplate from pydantic import Extra from sqlalchemy.engine import create_engine from trino.sqlalchemy import URL from sqlalchemy import * from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain from langchain.prompts.base import BasePromptTemplate from ubix.common.llm import get_llm easy_template = """ # Use the the schema links to generate the SQL queries for each of the questions. Q: "Find the buildings which have rooms with capacity more than 50." Schema_links: [classroom.building,classroom.capacity,50] SQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50 Q: "Find the room number of the rooms which can sit 50 to 100 students and their buildings." Schema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100] SQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100 Q: "Give the name of the student in the History department with the most credits." Schema_links: [student.name,student.dept_name,student.tot_cred,History] SQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1 Q: "Find the total budgets of the Marketing or Finance department." Schema_links: [department.budget,department.dept_name,Marketing,Finance] SQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance' Q: "Find the department name of the instructor whose name contains 'Soisalon'." Schema_links: [instructor.dept_name,instructor.name,Soisalon] SQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%' Q: "What is the name of the department with the most credits?" Schema_links: [course.dept_name,course.credits] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1 Q: "How many instructors teach a course in last year?" Schema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022] SQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022 Q: "Find the name of the students and their department names sorted by their total credits in ascending order." Schema_links: [student.name,student.dept_name,student.tot_cred] SQL: SELECT name , dept_name FROM student ORDER BY tot_cred Q: "Find the year which offers the largest number of courses." Schema_links: [SECTION.YEAR,SECTION.*] SQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1 Q: "What are the names and average salaries for departments with average salary higher than 42000?" Schema_links: [instructor.dept_name,instructor.salary,42000] SQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000 Q: "How many rooms in each building have a capacity of over 50?" Schema_links: [classroom.*,classroom.building,classroom.capacity,50] SQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building Q: "Find the names of the top 3 departments that provide the largest amount of courses?" Schema_links: [course.dept_name,course.*] SQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3 Q: "Find the maximum and average capacity among rooms in each building." Schema_links: [classroom.building,classroom.capacity] SQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building Q: "Find the title of the course that is offered by more than one department." Schema_links: [course.title] SQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1 Q: "show the revenues in last three year?" Schema_links: [product.avenue, 2022, 2019, product.date] SQL: SELECT year(product.date), max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(product.date) Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" schema_links: [{schema_links}] SQL: """ hard_template = """ Q: "Find the title of courses that have two prerequisites?" Schema_links: [course.title,course.course_id = prereq.course_id] SQL: SELECT course.title, prereq.course_id FROM course, prereq WHERE course.course_id = prereq.course_id GROUP BY prereq.course_id HAVING count(*) = 2 Q: "Find the total number of students and total number of instructors for each department." Schema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id] SQL: SELECT count(DISTINCT student.id), count(DISTINCT instructor.id), instructor.dept_name FROM department, student, instructor WHERE department.dept_name = instructor.dept_name and department.dept_name = student.dept_name GROUP BY instructor.dept_name Q: "What are salaries and by employees and cityname employees live in for the past three years?" Schema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR,employee.name,city.city_id=employee.city_id,city.name] SQL: SELECT year(company.YEAR),employee.name,city.name,sum(company.salary) FROM company,employee,city WHERE company.employee_id=employee.employee_id and city.city_id=employee.city_id and company.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(company.YEAR),employee.name,city.name Q: "Find the name of students who took any class in past three years" Schema_links: [student.name,student.id = takes.id,takes.YEAR] SQL: SELECT year(takes.YEAR),DISTINCT student.name FROM student,takes WHERE student.id = takes.id and takes.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(takes.YEAR) Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] Q: "{input}" Schema_links:{schema_links} SQL: """ product_schema = """ Q: "Show the revenue by product for past year" A: Let�~@~Ys think step by step. In the question "Show the revenues by product for past year", we are asked: "the revenue" so we need column = [invoice_items.netamount,invoice_items.productid,invoice_items.description] "by product" so we need column = [invoice_header.objectid] "for past year" so we need column = [invoice_header.creationdatetime] Based on the columns and tables, we need these Foreign_keys = [invoice_items.parentobjectid=invoice_header.objectid]. Based on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are: Schema_links: [invoice_items.netamount,invoice_items.productid,invoice_items.description,invoice_header.creationdatetime,invoice_items.parentobjectid=invoice_header.objectid,1] """ no_product_schema = """ Q: "Show the revenues by customer for past year" A: Let�~@~Ys think step by step. In the question "Show the revenues bycustomer for past year", we are asked: "the revenue" so we need column = [invoice_header.totalnetamount] "by customer" so we need column = [customercommon.businesspartnername,customer.objectid] "for past year" so we need column = [invoice_header.creationdatetime] Based on the columns and tables, we need these Foreign_keys = [customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid]. Based on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are: Schema_links: [invoice_header.totalnetamount,customercommon.businesspartnername,customer.objectid,invoice_header.creationdatetime,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid,1] """ schema_linking_prompt = """ Table Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country] Table Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code] Table Candidates, columns = [*,candidate_id,candidate_details] Table Courses, columns = [*,course_id,course_name,course_description,other_details] Table People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password] Table People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to] Table Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance] Table Student_Course_Registrations, columns = [*,student_id,course_id,registration_date] Table Students, columns = [*,student_id,student_details] Foreign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id] Q: "List the id of students who never attends courses?" A: Let’s think step by step. In the question "List the id of students who never attends courses?", we are asked: "id of students" so we need column = [Students.student_id] "never attends courses" so we need column = [Student_Course_Attendance.student_id] Based on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id]. Based on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are: Schema_links: [Students.student_id = Student_Course_Attendance.student_id] Table invoice_items, columns = [*,parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [*,objectid,creationdatetime,totalnetamount] Table customercommon, columns = [*,parentobjectid,businesspartnername] Table customer, columns = [*,objectid,uuid] Foreign_keys = [invoice_items.parentobjectid=invoice_header.objectid,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid] """ PROMPT = PromptTemplate( input_variables=["input", "schema_links"], template=easy_template, ) def format(sql): if "date" in sql: result = sql.replace("\'20", "TIMESTAMP \'20").replace("\"20", "TIMESTAMP \"20") return result else: return sql def hive_search(sql): hive_host = "trino" port = 8080 user_name = "hive" catalog="hive" #hive_database = "65057500bed4c2ac869fe964" #hive_database = "654a464f1dd821018bd47cd5" hive_database = "65487027ce6b72312eff28a2" engine = create_engine( URL( host=hive_host, port=port, user=user_name, catalog=catalog, schema=hive_database, ), ) with engine.connect() as con: sql = format(sql) #sql = "select count(*) from Invoice_Header;" #print(sql) result_t = con.execute(text(sql)) result = result_t.fetchall() return result class DIN_Chain(Chain): """ An example of a custom chain. """ prompt: BasePromptTemplate """Prompt object to use.""" llm: BaseLanguageModel output_key: str = "text" #: :meta private: class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Will be whatever keys the prompt expects. :meta private: """ return self.prompt.input_variables[:1] @property def output_keys(self) -> List[str]: """Will always return text key. :meta private: """ return [self.output_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: # Your custom chain logic goes here # This is just an example that mimics LLMChain #pdb.set_trace() from datetime import datetime schema_links_prompt = schema_linking_prompt_maker(inputs.get("input")) start = datetime.now() schema_links = self.llm(schema_links_prompt) end = datetime.now() print("schema links cost:", end - start) schema_links = schema_links.split("\n\n")[0].split("Schema_links: ")[1] #schema_links, is_hard = get_schema_links(inputs.get("input")) #schema_links = "[invoice_header.totalnetamount,invoice_header.creationdatetime]" inputs["schema_links"] = schema_links if "by" in inputs.get("input"): self.prompt.template = hard_template else: self.prompt.template = easy_template prompt_value = self.prompt.format_prompt(**inputs) start = datetime.now() # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = self.llm.generate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) #print(f'Original response:{response}') text = response.generations[0][0].text #pdb.set_trace() #print(f'Final Text:{text}') result_ = text.split("\n\n")[0] result_ = result_.replace("\n", " ") print(result_) key_list = [] for item in result_.split(" FROM")[0].split(","): item = item.replace(" ", "").replace(")", "") item = item.split(".") key_list.append(item[1]) end = datetime.now() print("llm generate cost:", end - start) start = datetime.now() final = hive_search(result_) res = [] for f_item in final: dct_item = {} try: for index, e_item in enumerate(f_item): dct_item[key_list[index]] = str(f_item[index]) except: pass res.append(dct_item) dct_final = res dct = {} dct["sql"] = result_ dct["answer"] = dct_final end = datetime.now() print("search cost:", end - start) print("============================") # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: run_manager.on_text("Log something about this run") return {self.output_key:dct} async def _acall( self, inputs: Dict[str, Any], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, str]: #print(f'DummyChain:{inputs}') # Your custom chain logic goes here # This is just an example that mimics LLMChain prompt_value = self.prompt.format_prompt(**inputs) # Whenever you call a language model, or another chain, you should pass # a callback manager to it. This allows the inner run to be tracked by # any callbacks that are registered on the outer run. # You can always obtain a callback manager for this by calling # `run_manager.get_child()` as shown below. response = await self.llm.agenerate_prompt( [prompt_value], callbacks=run_manager.get_child() if run_manager else None ) # If you want to log something about this run, you can do so by calling # methods on the `run_manager`, as shown below. This will trigger any # callbacks that are registered for that event. if run_manager: await run_manager.on_text("Log something about this run") return {self.output_key: response.generations[0][0].text} @property def _chain_type(self) -> str: return "my_custom_chain" def schema_linking_prompt_maker(test_sample_text): instruction = "# Find the schema_links for generating SQL queries for each question based on the database schema and Foreign keys.\n" fields = """ Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid] Table invoice_header, columns = [objectid,creationdatetime,totalnetamount] Table customercommon, columns = [parentobjectid,businesspartnername] Table customer, columns = [objectid,uuid,] """ foreign_keys = """ [invoice_items.parentobjectid=invoice_header.objectid,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid] """ global schema_linking_prompt if "product" in test_sample_text: schema_linking_prompt += product_schema else: schema_linking_prompt += no_product_schema prompt = instruction + schema_linking_prompt + fields +foreign_keys+ 'Q: "' + test_sample_text + """"\nA: Let’s think step by step.""" return prompt def get_din_chain(llm): chain = DIN_Chain(llm=llm, prompt=PROMPT) return chain if __name__ == "__main__": llm = get_llm() chain = get_din_chain(llm) pdb.set_trace() query = "What are our revenues for the past 3 years" #query = "I want the last 3 years of revenues" #query = "what are our revenues by product for the past 3 years" #query = "what are our revenues by customer for the past 3 years" #query = "Can you show me our monthly income statements for the last 12 months?" result = chain.run(query) print("query:", query) print(result) """ PYTHONPATH=. LLM_TYPE=din python ubix/chain/chain_din_sql.py """
[ "What is the name of the department with the most credits?", "Find the title of the course that is offered by more than one department.", "Spring", "\nQ: \"Show the revenue by product for past year\"\nA: Let�~@~Ys think step by step. In the question \"Show the revenues by product for past year\", we are asked:\n\"the revenue\" so we need column = [invoice_items.netamount,invoice_items.productid,invoice_items.description]\n\"by product\" so we need column = [invoice_header.objectid]\n\"for past year\" so we need column = [invoice_header.creationdatetime]\nBased on the columns and tables, we need these Foreign_keys = [invoice_items.parentobjectid=invoice_header.objectid].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are:\nSchema_links: [invoice_items.netamount,invoice_items.productid,invoice_items.description,invoice_header.creationdatetime,invoice_items.parentobjectid=invoice_header.objectid,1]\n", "\n# Use the the schema links to generate the SQL queries for each of the questions.\nQ: \"Find the buildings which have rooms with capacity more than 50.\"\nSchema_links: [classroom.building,classroom.capacity,50]\nSQL: SELECT DISTINCT building FROM classroom WHERE capacity > 50\n\nQ: \"Find the room number of the rooms which can sit 50 to 100 students and their buildings.\"\nSchema_links: [classroom.building,classroom.room_number,classroom.capacity,50,100]\nSQL: SELECT building , room_number FROM classroom WHERE capacity BETWEEN 50 AND 100\n\nQ: \"Give the name of the student in the History department with the most credits.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred,History]\nSQL: SELECT name FROM student WHERE dept_name = 'History' ORDER BY tot_cred DESC LIMIT 1\n\nQ: \"Find the total budgets of the Marketing or Finance department.\"\nSchema_links: [department.budget,department.dept_name,Marketing,Finance]\nSQL: SELECT sum(budget) FROM department WHERE dept_name = 'Marketing' OR dept_name = 'Finance'\n\nQ: \"Find the department name of the instructor whose name contains 'Soisalon'.\"\nSchema_links: [instructor.dept_name,instructor.name,Soisalon]\nSQL: SELECT dept_name FROM instructor WHERE name LIKE '%Soisalon%'\n\nQ: \"What is the name of the department with the most credits?\"\nSchema_links: [course.dept_name,course.credits]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY sum(credits) DESC LIMIT 1\n\nQ: \"How many instructors teach a course in last year?\"\nSchema_links: [teaches.ID,teaches.semester,teaches.YEAR,Spring,2022]\nSQL: SELECT COUNT (DISTINCT ID) FROM teaches WHERE semester = 'Spring' AND YEAR = 2022\n\nQ: \"Find the name of the students and their department names sorted by their total credits in ascending order.\"\nSchema_links: [student.name,student.dept_name,student.tot_cred]\nSQL: SELECT name , dept_name FROM student ORDER BY tot_cred\n\nQ: \"Find the year which offers the largest number of courses.\"\nSchema_links: [SECTION.YEAR,SECTION.*]\nSQL: SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY count(*) DESC LIMIT 1\n\nQ: \"What are the names and average salaries for departments with average salary higher than 42000?\"\nSchema_links: [instructor.dept_name,instructor.salary,42000]\nSQL: SELECT dept_name , AVG (salary) FROM instructor GROUP BY dept_name HAVING AVG (salary) > 42000\n\nQ: \"How many rooms in each building have a capacity of over 50?\"\nSchema_links: [classroom.*,classroom.building,classroom.capacity,50]\nSQL: SELECT count(*) , building FROM classroom WHERE capacity > 50 GROUP BY building\n\nQ: \"Find the names of the top 3 departments that provide the largest amount of courses?\"\nSchema_links: [course.dept_name,course.*]\nSQL: SELECT dept_name FROM course GROUP BY dept_name ORDER BY count(*) DESC LIMIT 3\n\nQ: \"Find the maximum and average capacity among rooms in each building.\"\nSchema_links: [classroom.building,classroom.capacity]\nSQL: SELECT max(capacity) , avg(capacity) , building FROM classroom GROUP BY building\n\nQ: \"Find the title of the course that is offered by more than one department.\"\nSchema_links: [course.title]\nSQL: SELECT title FROM course GROUP BY title HAVING count(*) > 1\n\nQ: \"show the revenues in last three year?\"\nSchema_links: [product.avenue, 2022, 2019, product.date]\nSQL: SELECT year(product.date), max(avenue) from product where date between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(product.date)\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nschema_links: [{schema_links}]\nSQL:\n", "What are the names and average salaries for departments with average salary higher than 42000?", "show the revenues in last three year?", "Find the year which offers the largest number of courses.", "Finance", "Find the total budgets of the Marketing or Finance department.", "Find the buildings which have rooms with capacity more than 50.", "Give the name of the student in the History department with the most credits.", "Find the room number of the rooms which can sit 50 to 100 students and their buildings.", "%Soisalon%", "input", "schema_links", "Find the department name of the instructor whose name contains 'Soisalon'.", "How many rooms in each building have a capacity of over 50?", "PLACEHOLDER", "# Find the schema_links for generating SQL queries for each question based on the database schema and Foreign keys.\n\nTable Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country]\nTable Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code]\nTable Candidates, columns = [*,candidate_id,candidate_details]\nTable Courses, columns = [*,course_id,course_name,course_description,other_details]\nTable People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password]\nTable People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to]\nTable Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance]\nTable Student_Course_Registrations, columns = [*,student_id,course_id,registration_date]\nTable Students, columns = [*,student_id,student_details]\nForeign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id]\nQ: \"List the id of students who never attends courses?\"\nA: Let’s think step by step. In the question \"List the id of students who never attends courses?\", we are asked:\n\"id of students\" so we need column = [Students.student_id]\n\"never attends courses\" so we need column = [Student_Course_Attendance.student_id]\nBased on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are:\nSchema_links: [Students.student_id = Student_Course_Attendance.student_id]\n\nTable invoice_items, columns = [*,parentobjectid,netamount,description,productid,partyuuid]\nTable invoice_header, columns = [*,objectid,creationdatetime,totalnetamount]\nTable customercommon, columns = [*,parentobjectid,businesspartnername]\nTable customer, columns = [*,objectid,uuid]\nForeign_keys = [invoice_items.parentobjectid=invoice_header.objectid,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid]\n\n Table invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n Table invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n Table customercommon, columns = [parentobjectid,businesspartnername]\n Table customer, columns = [objectid,uuid,]\n \n [invoice_items.parentobjectid=invoice_header.objectid,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid]\n Q: \"PLACEHOLDER\"\nA: Let’s think step by step.", "\nQ: \"Find the title of courses that have two prerequisites?\"\nSchema_links: [course.title,course.course_id = prereq.course_id]\nSQL: SELECT course.title, prereq.course_id FROM course, prereq WHERE course.course_id = prereq.course_id GROUP BY prereq.course_id HAVING count(*) = 2\n\nQ: \"Find the total number of students and total number of instructors for each department.\"\nSchema_links: [department.dept_name = student.dept_name,student.id,department.dept_name = instructor.dept_name,instructor.id]\nSQL: SELECT count(DISTINCT student.id), count(DISTINCT instructor.id), instructor.dept_name FROM department, student, instructor WHERE department.dept_name = instructor.dept_name and department.dept_name = student.dept_name GROUP BY instructor.dept_name\n\nQ: \"What are salaries and by employees and cityname employees live in for the past three years?\"\nSchema_links: [company.salary,company.employee_id=employee.employee_id,company.YEAR,employee.name,city.city_id=employee.city_id,city.name]\nSQL: SELECT year(company.YEAR),employee.name,city.name,sum(company.salary) FROM company,employee,city WHERE company.employee_id=employee.employee_id and city.city_id=employee.city_id and company.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(company.YEAR),employee.name,city.name\n\nQ: \"Find the name of students who took any class in past three years\"\nSchema_links: [student.name,student.id = takes.id,takes.YEAR]\nSQL: SELECT year(takes.YEAR),DISTINCT student.name FROM student,takes WHERE student.id = takes.id and takes.YEAR between '2019-01-01 00:00:00' and '2022-12-31 23:59:59' GROUP BY year(takes.YEAR)\n\nTable invoice_items, columns = [parentobjectid,netamount,description,productid,partyuuid]\n\nTable invoice_header, columns = [objectid,creationdatetime,totalnetamount]\n\nTable customercommon, columns = [parentobjectid,businesspartnername]\n\nTable customer, columns = [objectid,uuid,]\n\nQ: \"{input}\"\nSchema_links:{schema_links}\nSQL:\n", "2022-12-31 23:59:59", "How many instructors teach a course in last year?", "Marketing", "Find the maximum and average capacity among rooms in each building.", "{input}", "\nQ: \"Show the revenues by customer for past year\"\nA: Let�~@~Ys think step by step. In the question \"Show the revenues bycustomer for past year\", we are asked:\n\"the revenue\" so we need column = [invoice_header.totalnetamount]\n\"by customer\" so we need column = [customercommon.businesspartnername,customer.objectid]\n\"for past year\" so we need column = [invoice_header.creationdatetime]\nBased on the columns and tables, we need these Foreign_keys = [customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = [1]. So the Schema_links are:\nSchema_links: [invoice_header.totalnetamount,customercommon.businesspartnername,customer.objectid,invoice_header.creationdatetime,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid,1]\n", "Find the names of the top 3 departments that provide the largest amount of courses?", "\nTable Addresses, columns = [*,address_id,line_1,line_2,city,zip_postcode,state_province_county,country]\nTable Candidate_Assessments, columns = [*,candidate_id,qualification,assessment_date,asessment_outcome_code]\nTable Candidates, columns = [*,candidate_id,candidate_details]\nTable Courses, columns = [*,course_id,course_name,course_description,other_details]\nTable People, columns = [*,person_id,first_name,middle_name,last_name,cell_mobile_number,email_address,login_name,password]\nTable People_Addresses, columns = [*,person_address_id,person_id,address_id,date_from,date_to]\nTable Student_Course_Attendance, columns = [*,student_id,course_id,date_of_attendance]\nTable Student_Course_Registrations, columns = [*,student_id,course_id,registration_date]\nTable Students, columns = [*,student_id,student_details]\nForeign_keys = [Students.student_id = People.person_id,People_Addresses.address_id = Addresses.address_id,People_Addresses.person_id = People.person_id,Student_Course_Registrations.course_id = Courses.course_id,Student_Course_Registrations.student_id = Students.student_id,Student_Course_Attendance.student_id = Student_Course_Registrations.student_id,Student_Course_Attendance.course_id = Student_Course_Registrations.course_id,Candidates.candidate_id = People.person_id,Candidate_Assessments.candidate_id = Candidates.candidate_id]\nQ: \"List the id of students who never attends courses?\"\nA: Let’s think step by step. In the question \"List the id of students who never attends courses?\", we are asked:\n\"id of students\" so we need column = [Students.student_id]\n\"never attends courses\" so we need column = [Student_Course_Attendance.student_id]\nBased on the columns and tables, we need these Foreign_keys = [Students.student_id = Student_Course_Attendance.student_id].\nBased on the tables, columns, and Foreign_keys, The set of possible cell values are = []. So the Schema_links are:\nSchema_links: [Students.student_id = Student_Course_Attendance.student_id]\n\nTable invoice_items, columns = [*,parentobjectid,netamount,description,productid,partyuuid]\nTable invoice_header, columns = [*,objectid,creationdatetime,totalnetamount]\nTable customercommon, columns = [*,parentobjectid,businesspartnername]\nTable customer, columns = [*,objectid,uuid]\nForeign_keys = [invoice_items.parentobjectid=invoice_header.objectid,customer.uuid=invoice_header.partyuuid,customercommon.parentobjectid=customer.objectid]\n", "Find the name of the students and their department names sorted by their total credits in ascending order.", "2019-01-01 00:00:00" ]
2024-01-10
wofeichangaiwoai/din_sql_llm
test~tgi_test.py
from langchain.llms import HuggingFaceTextGenInference llm = HuggingFaceTextGenInference( inference_server_url="http://colossal-llm-api.home-dev.ubix.io", max_new_tokens=650, #top_k=10, #top_p=0.95, #typical_p=0.95, temperature=0.01, #repetition_penalty=1.03, ) print(llm.predict("hello, I'm felix")) """ python test/tgi_test.py """
[]
2024-01-10
IT20642914/Documentation-QA-using-LlamaIndex-and-Milvus
milvus_interaction.py
from flask import Flask, request, jsonify import csv import random import os import openai from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility import logging import colorlog from dotenv import load_dotenv import time # Load environment variables or set them directly MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') OPENAI_ENGINE = os.environ.get('OPENAI_ENGINE') OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY') # Set up the logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create a ColorFormatter for the logger formatter = colorlog.ColoredFormatter( '%(log_color)s%(levelname)s: %(message)s', log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) # Create a console handler and set the formatter console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) # Add the console handler to the logger logger.addHandler(console_handler) MILVUS_HOST = MILVUS_HOST MILVUS_PORT = MILVUS_PORT OPENAI_ENGINE = OPENAI_ENGINE openai.api_key = OPENAI_API_KEY # Extract the book titles def csv_load(file): with open(file, newline='') as f: reader = csv.reader(f, delimiter=',') for row in reader: yield row[1] # Embed text with error handling def embed_with_error_handling(text): try: embedding = openai.Embedding.create( input=text, engine=os.environ.get('OPENAI_ENGINE') )["data"][0]["embedding"] return embedding # Ensure this returns a list of numbers except Exception as e: logger.error(f"Error embedding text: {text}. Error: {str(e)}") return None def save_to_milvus(): current_directory = os.getcwd() FILE = 'csv/Questions Master _ ChildOther.csv' # Update the file path separator to '/' FilePath = os.path.join(current_directory, FILE) COLLECTION_NAME = 'title_db' DIMENSION = 1536 MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') # Connect to Milvus connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) logger.info("Connected to Milvus.") # Create collection schema and other setup steps... # Insert each title and its embedding with error handling collection = Collection(name=COLLECTION_NAME) # Create collection object # Assuming your Milvus collection expects three fields: 'id', 'title', 'embedding' for idx, text in enumerate(csv_load(FilePath)): logger.debug(f"Inserting text '{text}' with index '{idx}'.") embedding = embed_with_error_handling(text) if embedding is not None: ins = [ {'id': idx, 'title': text[:198] if len(text) > 200 else text, 'embedding': embedding} ] try: collection.insert(ins) logger.debug(f"Text '{text}' inserted successfully.") time.sleep(3) # Free OpenAI account limited to 60 RPM except Exception as e: logger.error(f"Error inserting text '{text}' into collection. Error: {str(e)}") # Load the collection into memory for searching collection.load() logger.info("Loaded collection into memory for searching.") return jsonify({"message": "File processed and data inserted into the collection."}) def search_in_milvus(search_term): search_term = search_term MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') # Connect to Milvus connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) logger.info("Connected to Milvus.") # Fetch all collections collections = utility.list_collections() logger.info("Collections in Milvus:") search_results_per_collection = {} for collection_name in collections: logger.info(f'collection_name: {collection_name}') # Search text in each collection search_results = search_in_collection(collection_name, search_term) # Store search results for this collection search_results_per_collection[collection_name] = search_results return jsonify({"results": search_results_per_collection}) def search_in_collection(collection_name, search_term): # Get the collection object collection = Collection(collection_name) def search_with_error_handling(text): try: logger.debug(f"Searching for text '{text}' in collection '{collection_name}'.") embedded_text = embed_with_error_handling(text) if embedded_text: search_params = {"metric_type": "L2"} results = collection.search( data=[embedded_text], anns_field="embedding", param=search_params, limit=5, output_fields=['title'] ) ret = [] for hit in results[0]: row = [hit.id, hit.score, hit.entity.get('title')] ret.append(row) return ret else: return [] except Exception as e: logger.error(f"Error searching for text '{text}' in collection '{collection_name}'. Error: {str(e)}") return [] # Perform searches using only the provided search term search_results = search_with_error_handling(search_term) return {search_term: search_results} if search_results else {}
[]
2024-01-10
IT20642914/Documentation-QA-using-LlamaIndex-and-Milvus
testapp.py
from flask import Flask, request, jsonify import csv import random import os import pandas as pd import openai from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility import logging import colorlog from dotenv import load_dotenv import time load_dotenv() app = Flask(__name__) # Set up the logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create a ColorFormatter for the logger formatter = colorlog.ColoredFormatter( '%(log_color)s%(levelname)s: %(message)s', log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } ) # Create a console handler and set the formatter console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) # Add the console handler to the logger logger.addHandler(console_handler) # Extract the book titles def csv_load(filepath): with open(filepath, newline='') as f: reader = csv.reader(f, delimiter=',') for row in reader: yield row # Yield entire row # Embed text with error handling def embed_with_error_handling(text): try: embedding = openai.Embedding.create( input=text, engine=os.environ.get('OPENAI_ENGINE') )["data"][0]["embedding"] return embedding # Ensure this returns a list of numbers except Exception as e: logger.error(f"Error embedding text: {text}. Error: {str(e)}") return None @app.route('/search', methods=['GET']) def search(): search_term = request.args.get('q') MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') # Connect to Milvus connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) logger.info("Connected to Milvus.") # Fetch all collections collections = utility.list_collections() logger.info("Collections in Milvus:") search_results_per_collection = {} for collection_name in collections: logger.info(f'collection_name: {collection_name}') # Search text in each collection search_results = search_in_collection(collection_name, search_term) # Store search results for this collection search_results_per_collection[collection_name] = search_results return jsonify({"results": search_results_per_collection}) def search_in_collection(collection_name, search_term): # Get the collection object collection = Collection(collection_name) def search_with_error_handling(text): try: logger.debug(f"Searching for text '{text}' in collection '{collection_name}'.") embedded_text = embed_with_error_handling(text) if embedded_text: search_params = {"metric_type": "L2"} results = collection.search( data=[embedded_text], anns_field="embedding", param=search_params, limit=1, output_fields=['title'] ) ret = [] for hit in results[0]: row = [hit.id, hit.score, hit.entity.get('title')] ret.append(row) return ret else: return [] except Exception as e: logger.error(f"Error searching for text '{text}' in collection '{collection_name}'. Error: {str(e)}") return [] # Perform searches using only the provided search term search_results = search_with_error_handling(search_term) return {search_term: search_results} if search_results else {} # Endpoint to delete a collection @app.route('/delete_collection', methods=['DELETE']) def delete_collection(): collection_name = request.args.get('collection_name') # Get Milvus connection parameters MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') # Connect to Milvus connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) # Check if the collection exists if utility.has_collection(collection_name): utility.drop_collection(collection_name) logger.info(f"Collection '{collection_name}' deleted successfully.") return jsonify({"message": f"Collection '{collection_name}' deleted successfully."}), 200 else: return jsonify({"message": f"Collection '{collection_name}' does not exist."}), 404 # Endpoint to get a list of collections @app.route('/collections', methods=['GET']) def get_collections(): # Get Milvus connection parameters MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') # Connect to Milvus connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) # Fetch all collections collections = utility.list_collections() logger.info("collections:{collections}}") return jsonify({"collections": collections}), 200 def handle_empty_values(value): # Check if the value is empty or null if pd.isnull(value) or value == '': # If the value is empty or null, replace it with a default string value or handle it based on your use case return 'N/A' # For example, replacing empty values with 'N/A' else: return str(value) def create_collection_schema(header): fields = [ FieldSchema( name=col_name, dtype=DataType.INT64 if col_name == 'question_id' else DataType.VARCHAR, is_primary=True if col_name == 'question_id' else False, max_length=256 if col_name != 'question_id' else None ) for col_name in header ] logger.info(f"fields:{fields}") fields.append(FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=512)) return CollectionSchema(fields=fields, description="Dynamic Collection from CSV") def process_csv_data(file, collection): logger.info(f"Processing CSV data from file: {file}") with open(file, newline='') as f: logger.info(f"Opened file: {file}") reader = csv.reader(f) header = next(reader) logger.info(f"Processing CSV data - header: {header}") data_to_insert = [] for row in reader: row_dict = {header[i]: row[i] for i in range(len(header))} text = row_dict['question_id'] logger.info(f"Text to Embedding: {text}") try: embedding_response = openai.Embedding.create(input=text, engine="text-embedding-ada-002") logger.info(f"Embedding API Response: {embedding_response}") if 'data' in embedding_response and embedding_response['data']: embedding = embedding_response['data'][0]['embedding'] logger.info(f"Embedding: {embedding}") if isinstance(embedding, list) and len(embedding) > 0: row_dict['embedding'] = embedding else: logger.error("Invalid embedding data received.") row_dict['embedding'] = 'N/A' # Set a default value if embedding creation fails else: logger.error("No valid data received from the Embedding API.") row_dict['embedding'] = 'N/A' # Set a default value if embedding creation fails except Exception as embedding_error: logger.error(f"Embedding creation error: {str(embedding_error)}") row_dict['embedding'] = 'N/A' # Set a default value if embedding creation fails data_to_insert.append(row_dict) try: collection.insert(data_to_insert) logger.info("Data inserted into collection successfully") except Exception as insert_error: logger.error(f"Data insertion error: {str(insert_error)}") @app.route('/create_and_store_data', methods=['POST']) def create_and_store_data(): file = 'csv/Questions Master _ ChildOther.csv' collection_name = 'QuestionsMaster_ChildOther' MILVUS_HOST = os.environ.get('MILVUS_HOST') MILVUS_PORT = os.environ.get('MILVUS_PORT') OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY') openai.api_key = OPENAI_API_KEY try: # Establish Milvus connection connections.connect(host=MILVUS_HOST, port=MILVUS_PORT) except Exception as milvus_conn_error: logger.error(f"Milvus connection error: {str(milvus_conn_error)}") return jsonify({"error": f"Milvus connection error: {str(milvus_conn_error)}"}), 500 try: # List collections collections = utility.list_collections() if collection_name not in collections: schema = create_collection_schema(pd.read_csv(file).columns) collection = Collection(name=collection_name, schema=schema) collection.create() process_csv_data(file, collection) return jsonify({"message": f"Collection '{collection_name}' created and data stored successfully."}), 201 else: collection = Collection(name=collection_name) process_csv_data(file, collection) return jsonify({"message": f"Collection '{collection_name}' already exists. Data inserted successfully."}), 200 except Exception as collection_error: logger.error(f"Collection creation or insertion error: {str(collection_error)}") return jsonify({"error": f"Collection creation or insertion error: {str(collection_error)}"}), 500 if __name__ == '__main__': app.run(debug=True)
[]
2024-01-10
trobutlef/CalHacks23-OpenAI
backend~audio_processing.py
import openai from pydub import AudioSegment from pydub.utils import make_chunks import os import credentials from dotenv import load_dotenv openai.api_key = 'sk-VkruRhbsDhZTJ8NgFM4YT3BlbkFJvzysIPK8GlZC9Qj8XQXt0' # Get the current directory path current_directory = os.getcwd() # Directory where the chunks are stored chunks_directory = os.path.join(current_directory, 'chunks') def split_audio(audio_path, chunk_length_ms=25000): audio = AudioSegment.from_file(audio_path) chunks = make_chunks(audio, chunk_length_ms) # Make chunks of one sec #Export all of the individual chunks as wav files for i, chunk in enumerate(chunks): chunk_name = "chunk{0}.wav".format(i) print ("exporting", chunk_name) chunk.export(os.path.join(chunks_directory, chunk_name), format="wav") def process_audio(audio_path): # Split the audio into chunks split_audio(audio_path) # Initialize an empty string to store the full transcript full_transcript = "" # Loop over each chunk for i in range(len(os.listdir(chunks_directory))): # Construct the path to the chunk chunk_path = os.path.join(chunks_directory, f"chunk{i}.wav") # Open the chunk with open(chunk_path, "rb") as audio_file: # Transcribe the chunk response = openai.Audio.transcribe("whisper-1", audio_file, response_format="srt") # Add the chunk's transcript to the full transcript full_transcript += response # Write the full transcript to a file with open("transcript.txt", "w", encoding='utf-8') as transcript_file: transcript_file.write(full_transcript) # Return the full transcript return full_transcript
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Ca_multi_function_weatherGPT.py
import json import openai from decouple import config from apis.weather import get_current_weather, get_weather_forecast from func_descriptions.weather import ( describe_get_current_weather, describe_get_weather_forecast, ) from utils.printer import ColorPrinter as Printer openai.api_key = config("CHATGPT_API_KEY") def ask_chat_gpt(query): messages = [ {"role": "user", "content": query}, ] functions = [describe_get_current_weather, describe_get_weather_forecast] first_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, functions=functions, function_call="auto", # auto is default )["choices"][0]["message"] messages.append(first_response) if first_response.get("function_call"): available_functions = { "get_current_weather_in_location": get_current_weather, "get_weather_forecast_in_location": get_weather_forecast, } function_name = first_response["function_call"]["name"] function_to_call = available_functions[function_name] function_args = json.loads(first_response["function_call"]["arguments"]) function_response = function_to_call(**function_args) messages.append( { "role": "function", "name": function_name, "content": function_response, } ) second_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, )["choices"][0]["message"] messages.append(second_response) Printer.color_print(messages) return second_response["content"] Printer.color_print(messages) return first_response["content"] print(ask_chat_gpt("What is the weather forecast in Leipzig for the coming 3 days?"))
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Aa_get_joke.py
from decouple import config import openai openai.api_key = config("CHATGPT_API_KEY") JOKE_SETUP = "I will give you a subject each time for all the following prompts. You will return to me a joke, but it should not be too long (4 lines at most). Please do not provide an introduction like 'Here's a joke for you' but get straight into the joke." def get_joke(query): result = openai.ChatCompletion.create( model="gpt-3.5-turbo", temperature=0.4, max_tokens=200, messages=[ {"role": "system", "content": JOKE_SETUP}, {"role": "user", "content": query}, ], ) return result["choices"][0]["message"]["content"] print(get_joke("Penguins"))
[ "I will give you a subject each time for all the following prompts. You will return to me a joke, but it should not be too long (4 lines at most). Please do not provide an introduction like 'Here's a joke for you' but get straight into the joke." ]
2024-01-10
finxter/openai_function_calls_and_embeddings
Ab_get_joke_w_function.py
import openai from decouple import config from apis.random_word import get_random_word from utils.printer import ColorPrinter as Printer openai.api_key = config("CHATGPT_API_KEY") JOKE_SETUP = """ You will be given a subject by the user. You will return a joke, but it should not be too long (4 lines at most). You will not provide an introduction like 'Here's a joke for you' but get straight into the joke. There is a function called 'get_random_word'. If the user does not provide a subject, you should call this function and use the result as the subject. If the user does provide a subject, you should not call this function. The only exception is if the user asks for a random joke, in which case you should call the function and use the result as the subject. Example: {user: 'penguins'} = Do not call the function => provide a joke about penguins. Example: {user: ''} = Call the function => provide a joke about the result of the function. Example: {user: 'soul music'} = Do not call the function => provide a joke about soul music. Example: {user: 'random'} = Call the function => provide a joke about the result of the function. Example: {user: 'guitars'} = Do not call the function => provide a joke about guitars. Example: {user: 'give me a random joke'} = Call the function => provide a joke about the result of the function. """ def get_joke_result(query): messages = [ {"role": "system", "content": JOKE_SETUP}, {"role": "user", "content": query}, ] functions = [ { "name": "get_random_word", "description": "Get a subject for your joke.", "parameters": { "type": "object", "properties": { "number_of_words": { "type": "integer", "description": "The number of words to generate.", } }, }, } ] first_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, functions=functions, function_call="auto", # auto is default )["choices"][0]["message"] messages.append(first_response) if first_response.get("function_call"): function_response = get_random_word() messages.append( { "role": "function", "name": "get_random_word", "content": function_response, } ) second_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, )["choices"][0]["message"] messages.append(second_response) Printer.color_print(messages) return second_response["content"] Printer.color_print(messages) return first_response["content"] print(get_joke_result(""))
[ "\nYou will be given a subject by the user. You will return a joke, but it should not be too long (4 lines at most). You will not provide an introduction like 'Here's a joke for you' but get straight into the joke.\nThere is a function called 'get_random_word'. If the user does not provide a subject, you should call this function and use the result as the subject. If the user does provide a subject, you should not call this function. The only exception is if the user asks for a random joke, in which case you should call the function and use the result as the subject.\nExample: {user: 'penguins'} = Do not call the function => provide a joke about penguins.\nExample: {user: ''} = Call the function => provide a joke about the result of the function.\nExample: {user: 'soul music'} = Do not call the function => provide a joke about soul music.\nExample: {user: 'random'} = Call the function => provide a joke about the result of the function.\nExample: {user: 'guitars'} = Do not call the function => provide a joke about guitars.\nExample: {user: 'give me a random joke'} = Call the function => provide a joke about the result of the function.\n" ]
2024-01-10
finxter/openai_function_calls_and_embeddings
Bb_chatgpt_with_live_weather.py
import json import openai from decouple import config from apis.weather import get_current_weather from func_descriptions.weather import describe_get_current_weather from utils.printer import ColorPrinter as Printer openai.api_key = config("CHATGPT_API_KEY") def ask_chat_gpt(query): messages = [ {"role": "user", "content": query}, ] functions = [describe_get_current_weather] first_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, functions=functions, function_call="auto", # auto is default )["choices"][0]["message"] messages.append(first_response) if first_response.get("function_call"): available_functions = { "get_current_weather_in_location": get_current_weather, } function_name = first_response["function_call"]["name"] function_to_call = available_functions[function_name] function_args = json.loads(first_response["function_call"]["arguments"]) function_response = function_to_call( location=function_args.get("location"), ) messages.append( { "role": "function", "name": "get_current_weather_in_location", "content": function_response, } ) second_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, )["choices"][0]["message"] messages.append(second_response) Printer.color_print(messages) return second_response["content"] Printer.color_print(messages) return first_response["content"] print(ask_chat_gpt("What is the weather in Amsterdam?"))
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Ba_chatgpt_no_weather.py
from decouple import config import openai openai.api_key = config("CHATGPT_API_KEY") def ask_chat_gpt(query): result = openai.ChatCompletion.create( model="gpt-3.5-turbo", temperature=0.4, messages=[ {"role": "user", "content": query}, ], ) return result["choices"][0]["message"]["content"] print(ask_chat_gpt("What is the weather in Seoul?"))
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Fc_quote_embeddings.py
import openai import pandas as pd from decouple import config from Fx_quotes import quotes openai.api_key = config("CHATGPT_API_KEY") EMBEDDING_MODEL = "text-embedding-ada-002" total_tokens_used = 0 total_embeddings = 0 def get_quote_embedding(quote): global total_tokens_used, total_embeddings response = openai.Embedding.create( model=EMBEDDING_MODEL, input=quote, ) tokens_used = response["usage"]["total_tokens"] total_tokens_used += tokens_used total_embeddings += 1 if (total_embeddings % 10) == 0: print( f"Generated {total_embeddings} embeddings so far with a total of {total_tokens_used} tokens used. ({int((total_embeddings / len(quotes)) * 100)}%)" ) return response["data"][0]["embedding"] embedding_df = pd.DataFrame(columns=["quote", "author", "embedding"]) for index, quote in enumerate(quotes): current_quote = quote[0] try: current_author = quote[1] except IndexError: current_author = "Unknown" embedding = get_quote_embedding(current_quote) embedding_df.loc[index] = [current_quote, current_author, embedding] embedding_df.to_csv("Fx_embedding_db.csv", index=False) print( f""" Generated {total_embeddings} embeddings with a total of {total_tokens_used} tokens used. (Done!) Succesfully saved embeddings to embedding_db.csv, printing dataframe head: {embedding_df.head(5)} """ )
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Fb_getting_an_embedding.py
import openai from decouple import config openai.api_key = config("CHATGPT_API_KEY") EMBEDDING_MODEL = "text-embedding-ada-002" def get_quote_embedding(quote): response = openai.Embedding.create( model=EMBEDDING_MODEL, input=quote, ) return response print(get_quote_embedding("Please embed this sentence for me!"))
[]
2024-01-10
finxter/openai_function_calls_and_embeddings
Fd_find_nearest_quotes.py
import openai import numpy as np import pandas as pd from decouple import config from openai.embeddings_utils import cosine_similarity openai.api_key = config("CHATGPT_API_KEY") EMBEDDING_MODEL = "text-embedding-ada-002" def get_quote_embedding(quote): response = openai.Embedding.create( model=EMBEDDING_MODEL, input=quote, ) return response["data"][0]["embedding"] df = pd.read_csv("Fx_embedding_db.csv") df["embedding"] = df.embedding.apply(eval).apply(np.array) def find_similar_quotes(user_input, number_of_results=5): user_embedding = get_quote_embedding(user_input) df["similarity"] = df.embedding.apply( lambda embedding: cosine_similarity(embedding, user_embedding) ) result = df.sort_values(by="similarity", ascending=False).head(number_of_results) for i in range(number_of_results): print( f"{i+1}: {result.iloc[i]['quote']} - {result.iloc[i]['author']} ({result.iloc[i]['similarity']})" ) return result try: while True: print( "Welcome to the quote finder! Please enter a quote to find similar quotes." ) user_quote = input("Enter a quote or press ctrl+c to exit: ") result = find_similar_quotes(user_quote) except KeyboardInterrupt: print("Exiting...")
[]
2024-01-10
RicardoMicale/ProyectoEmergente
atari_wrappers.py
# taken from OpenAI baselines. import numpy as np import gym class MaxAndSkipEnv(gym.Wrapper): def __init__(self, env, skip=4): """Return only every `skip`-th frame""" gym.Wrapper.__init__(self, env) # most recent raw observations (for max pooling across time steps) self._obs_buffer = np.zeros( (2,) + env.observation_space.shape, dtype=np.uint8) self._skip = skip def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: self._obs_buffer[1] = obs total_reward += reward if done: break # Note that the observation on the done=True frame # doesn't matter max_frame = self._obs_buffer.max(axis=0) return max_frame, total_reward, done, info def reset(self, **kwargs): return self.env.reset(**kwargs) class ClipRewardEnv(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): """Bin reward to {+1, 0, -1} by its sign.""" return np.sign(reward) class FireResetEnv(gym.Wrapper): def __init__(self, env): """Take action on reset for environments that are fixed until firing.""" gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3 def reset(self, **kwargs): self.env.reset(**kwargs) obs, _, done, _ = self.env.step(1) if done: self.env.reset(**kwargs) obs, _, done, _ = self.env.step(2) if done: self.env.reset(**kwargs) return obs def step(self, ac): return self.env.step(ac) class EpisodicLifeEnv(gym.Wrapper): def __init__(self, env): """Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation. """ gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = True def step(self, action): obs, reward, done, info = self.env.step(action) self.was_real_done = done # check current lives, make loss of life terminal, # then update lives to handle bonus lives lives = self.env.unwrapped.ale.lives() if lives < self.lives and lives > 0: # for Qbert sometimes we stay in lives == 0 condition for a few frames # so it's important to keep lives > 0, so that we only reset once # the environment advertises done. done = True self.lives = lives return obs, reward, done, info def reset(self, **kwargs): """Reset only when lives are exhausted. This way all states are still reachable even though lives are episodic, and the learner need not know about any of this behind-the-scenes. """ if self.was_real_done: obs = self.env.reset(**kwargs) else: # no-op step to advance from terminal/lost life state obs, _, _, _ = self.env.step(0) self.lives = self.env.unwrapped.ale.lives() return obs # in torch imgs have shape [c, h, w] instead of common [h, w, c] class AntiTorchWrapper(gym.ObservationWrapper): def __init__(self, env): gym.ObservationWrapper.__init__(self, env) self.img_size = [env.observation_space.shape[i] for i in [1, 2, 0] ] self.observation_space = gym.spaces.Box(0.0, 1.0, self.img_size) def observation(self, img): """what happens to each observation""" img = img.transpose(1, 2, 0) return img
[]
2024-01-10
Anchoret13/Throw
train_HER.py
import numpy as np import gym import os, sys from mpi4py import MPI import pdb from HER.arguments import get_args import random import torch sys.path.append('./pybullet_env') # from pybullet_env import environment, utilities, robot # from environment import make_throwing_env from save_state_env import make_throwing_env # from pybullet_env.utilities import * # from gym_extensions.continuous.gym_navigation_2d.env_generator import Environment, EnvironmentCollection, Obstacle # from gym_extensions.continuous.gym_navigation_2d.env_generator import Environment#, EnvironmentCollection, Obstacle # from environments.velocity_env import MultiGoalEnvironment, CarEnvironment # from environments.car_env import RotationEnv, NewCarEnv, SimpleMovementEnvironment # from environments.torus_env import Torus # from environments.continuous_acrobot import ContinuousAcrobotEnv import pickle from gym.wrappers.time_limit import TimeLimit from action_randomness_wrapper import ActionRandomnessWrapper, RepeatedActionWrapper """ train the agent, the MPI part code is copy from openai baselines(https://github.com/openai/baselines/blob/master/baselines/her) """ LOGGING = True def get_env_params(env): obs = env.reset() # close the environment params = {'obs': obs['observation'].shape[0], 'goal': obs['desired_goal'].shape[0], 'action': env.action_space.shape[0], 'action_max': env.action_space.high[0], } params['max_timesteps'] = env._max_episode_steps return params def launch(args): # create the ddpg_agent if args.env_name == "MultiGoalEnvironment": env = MultiGoalEnvironment("MultiGoalEnvironment", time=True, vel_goal=False) elif args.env_name == "MultiGoalEnvironmentVelGoal": env = MultiGoalEnvironment("MultiGoalEnvironment", time=True, vel_goal=True) elif "Car" in args.env_name: # env = CarEnvironment("CarEnvironment", time=True, vel_goal=False) env = TimeLimit(NewCarEnv(vel_goal=False), max_episode_steps=50) # env = TimeLimit(CarEnvironment("CarEnvironment", time=True, vel_goal=False), max_episode_steps=50) elif args.env_name == "Asteroids" : env = TimeLimit(RotationEnv(vel_goal=False), max_episode_steps=50) elif args.env_name == "AsteroidsVelGoal" : env = TimeLimit(RotationEnv(vel_goal=True), max_episode_steps=50) elif "SimpleMovement" in args.env_name: env = TimeLimit(SimpleMovementEnvironment(vel_goal=False), max_episode_steps=50) elif args.env_name == "PendulumGoal": env = TimeLimit(PendulumGoalEnv(g=9.8), max_episode_steps=200) elif args.env_name == "Throwing": env = TimeLimit(make_throwing_env(), max_episode_steps=20) elif "Gridworld" in args.env_name: # from continuous_gridworld import create_map_1#, random_blocky_map, two_door_environment, random_map # from alt_gridworld_implementation import create_test_map, random_blocky_map, two_door_environment, random_map #create_map_1, from environments.solvable_gridworld_implementation import create_test_map, random_blocky_map, two_door_environment, random_map #create_map_1, # from gridworld_reimplementation import random_map max_steps = 50 if "Alt" in args.env_name else 20 if args.env_name == "TwoDoorGridworld": env=TimeLimit(two_door_environment(), max_episode_steps=50) else: if "RandomBlocky" in args.env_name: mapmaker = random_blocky_map elif "Random" in args.env_name: mapmaker = random_map elif "Test" in args.env_name: mapmaker = create_test_map else: mapmaker = create_map_1 if "Asteroids" in args.env_name: env_type="asteroids" elif "StandardCar" in args.env_name: env_type = "standard_car" elif "Car" in args.env_name: env_type = "car" else: env_type = "linear" print(f"env type: {env_type}") env = TimeLimit(mapmaker(env_type=env_type), max_episode_steps=max_steps) elif "ContinuousAcrobot" in args.env_name: env = TimeLimit(ContinuousAcrobotEnv(), max_episode_steps=50) elif "2DNav" in args.env_name or "2Dnav" in args.env_name: env = gym.make("Limited-Range-Based-Navigation-2d-Map8-Goal0-v0") else: env = gym.make(args.env_name) env = ActionRandomnessWrapper(env, args.action_noise) try: env.seed(args.seed + MPI.COMM_WORLD.Get_rank()) except: pass random.seed(args.seed + MPI.COMM_WORLD.Get_rank()) np.random.seed(args.seed + MPI.COMM_WORLD.Get_rank()) torch.manual_seed(args.seed + MPI.COMM_WORLD.Get_rank()) if args.cuda: torch.cuda.manual_seed(args.seed + MPI.COMM_WORLD.Get_rank()) # get the environment parameters env_params = get_env_params(env) # create the ddpg agent to interact with the environment ddpg_trainer = ddpg_agent(args, env, env_params) if args.resume == True: ddpg_trainer.resume_learning() else: ddpg_trainer.learn() # ddpg_trainer.learn() return ddpg_trainer if __name__ == '__main__': # take the configuration for the HER os.environ['OMP_NUM_THREADS'] = '1' os.environ['MKL_NUM_THREADS'] = '1' os.environ['IN_MPI'] = '1' # get the params args = get_args() # print(args) # exit() # from HER.rl_modules.generalized_usher_with_ratio_2 import ddpg_agent from HER.rl_modules.generalized_usher_resume_test import ddpg_agent suffix = "" agent = launch(args) n = 10 # success_rate, reward, value = ev['success_rate'], ev['reward_rate'], ev['value_rate'] success_rate = sum([agent._eval_agent(final=True)['success_rate'] for _ in range(n)])/n if LOGGING and MPI.COMM_WORLD.Get_rank() == 0: # pdb.set_trace() log_file_name = f"logging/{args.env_name}.txt" # success_rate = sum([agent._eval_agent()[0] for _ in range(n)])/n text = f"action_noise: {args.action_noise}, \ttwo_goal: {args.two_goal}, \tsuccess_rate: {success_rate}\n" with open(log_file_name, "a") as f: f.write(text) print("Log written")
[]
2024-01-10
thunlp/CorefBERT
transformers~tokenization_auto.py
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed 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. """ Auto Model class. """ from __future__ import absolute_import, division, print_function, unicode_literals import logging from .tokenization_bert import BertTokenizer from .tokenization_openai import OpenAIGPTTokenizer from .tokenization_gpt2 import GPT2Tokenizer from .tokenization_ctrl import CTRLTokenizer from .tokenization_transfo_xl import TransfoXLTokenizer from .tokenization_xlnet import XLNetTokenizer from .tokenization_xlm import XLMTokenizer from .tokenization_roberta import RobertaTokenizer from .tokenization_distilbert import DistilBertTokenizer #from .tokenization_camembert import CamembertTokenizer logger = logging.getLogger(__name__) class AutoTokenizer(object): r""":class:`~transformers.AutoTokenizer` is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when created with the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` class method. The `from_pretrained()` method take care of returning the correct tokenizer class instance using pattern matching on the `pretrained_model_name_or_path` string. The tokenizer class to instantiate is selected as the first pattern matching in the `pretrained_model_name_or_path` string (in the following order): - contains `camembert`: CamembertTokenizer (CamemBERT model) - contains `distilbert`: DistilBertTokenizer (DistilBert model) - contains `roberta`: RobertaTokenizer (RoBERTa model) - contains `bert`: BertTokenizer (Bert model) - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model) - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model) - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model) - contains `xlnet`: XLNetTokenizer (XLNet model) - contains `xlm`: XLMTokenizer (XLM model) This class cannot be instantiated using `__init__()` (throw an error). """ def __init__(self): raise EnvironmentError("AutoTokenizer is designed to be instantiated " "using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.") @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): r""" Instantiate a one of the tokenizer classes of the library from a pre-trained model vocabulary. The tokenizer class to instantiate is selected as the first pattern matching in the `pretrained_model_name_or_path` string (in the following order): - contains `camembert`: CamembertTokenizer (CamemBERT model) - contains `distilbert`: DistilBertTokenizer (DistilBert model) - contains `roberta`: RobertaTokenizer (RoBERTa model) - contains `bert`: BertTokenizer (Bert model) - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model) - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model) - contains `ctrl`: CTRLTokenizer (Salesforce CTRL model) - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model) - contains `xlnet`: XLNetTokenizer (XLNet model) - contains `xlm`: XLMTokenizer (XLM model) Params: pretrained_model_name_or_path: either: - a string with the `shortcut name` of a predefined tokenizer to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing vocabulary files required by the tokenizer, for instance saved using the :func:`~transformers.PreTrainedTokenizer.save_pretrained` method, e.g.: ``./my_model_directory/``. - (not applicable to all derived classes) a path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (e.g. Bert, XLNet), e.g.: ``./my_model_directory/vocab.txt``. cache_dir: (`optional`) string: Path to a directory in which a downloaded predefined tokenizer vocabulary files should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the vocabulary files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. inputs: (`optional`) positional arguments: will be passed to the Tokenizer ``__init__`` method. kwargs: (`optional`) keyword arguments: will be passed to the Tokenizer ``__init__`` method. Can be used to set special tokens like ``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``, ``additional_special_tokens``. See parameters in the doc string of :class:`~transformers.PreTrainedTokenizer` for details. Examples:: tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') # Download vocabulary from S3 and cache. tokenizer = AutoTokenizer.from_pretrained('./test/bert_saved_model/') # E.g. tokenizer was saved using `save_pretrained('./test/saved_model/')` """ if 'distilbert' in pretrained_model_name_or_path: return DistilBertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'camembert' in pretrained_model_name_or_path: return CamembertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'roberta' in pretrained_model_name_or_path: return RobertaTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'bert' in pretrained_model_name_or_path: return BertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'openai-gpt' in pretrained_model_name_or_path: return OpenAIGPTTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'gpt2' in pretrained_model_name_or_path: return GPT2Tokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'transfo-xl' in pretrained_model_name_or_path: return TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'xlnet' in pretrained_model_name_or_path: return XLNetTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'xlm' in pretrained_model_name_or_path: return XLMTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) elif 'ctrl' in pretrained_model_name_or_path: return CTRLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) raise ValueError("Unrecognized model identifier in {}. Should contains one of " "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " "'xlm', 'roberta', 'camembert', 'ctrl'".format(pretrained_model_name_or_path))
[]
2024-01-10
owebb1/research-summarizer
starter.py
import arxiv import dotenv import os from langchain.agents.agent_toolkits import GmailToolkit from langchain.agents import initialize_agent, AgentType from langchain.chat_models import ChatOpenAI from langchain.prompts import PromptTemplate from langchain import LLMChain from langchain.callbacks import get_openai_callback dotenv.load_dotenv() OPEN_AI_API_KEY = os.getenv("OPEN_AI_API_KEY") # Topic of the newsletter you want to write about query = "LLM" search = arxiv.Search( query=query, max_results=4, sort_by=arxiv.SortCriterion.SubmittedDate ) docs = "" for result in search.results(): docs += "Title: " + result.title + "\n" docs += "Abstract: " + result.summary + "\n" docs += "Download URL: " + result.pdf_url + "\n" print(result.links) for link in result.links: docs += "Links: " + link.href + "\n" # Track cost with get_openai_callback() as cb: # Template for the newsletter prompt_newsletter_template = """ You are a newsletter writer. You write newsletters about scientific articles. You introduce the article and show a small summary to tell the user what the article is about. You're main goal is to write a newsletter which contains summaries to interest the user in the articles. -------------------- {text} -------------------- Start with the title of the article. Then, write a small summary of the article. Below each summary, include the link to the article containing /abs/ in the URL. Summaries: """ PROMPT_NEWSLETTER = PromptTemplate( template=prompt_newsletter_template, input_variables=["text"]) # Initialize the language model llm = ChatOpenAI( temperature=0.6, model_name="gpt-3.5-turbo-16k", verbose=True) # Initialize the LLMChain newsletter_chain = LLMChain( llm=llm, prompt=PROMPT_NEWSLETTER, verbose=True) # Run the LLMChain newsletter = newsletter_chain.run(docs) # Write newsletter to a text file with open("newsletter.txt", "w") as f: f.write(newsletter) # Set toolkit toolkit = GmailToolkit() # Initialize the Gmail agent agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) # Run the agent instructions = f""" Send an email to [email protected]. The subject should be 'Scientific Newsletter about {query}'. The content should be the following: {newsletter}. """ agent.run(instructions) print(cb)
[ "\n You are a newsletter writer. You write newsletters about scientific articles. You introduce the article and show a small summary to tell the user what the article is about.\n\n You're main goal is to write a newsletter which contains summaries to interest the user in the articles.\n\n --------------------\n {text}\n --------------------\n\n Start with the title of the article. Then, write a small summary of the article.\n\n Below each summary, include the link to the article containing /abs/ in the URL.\n\n Summaries:\n\n " ]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~chat_prompt.py
import asyncio from typing import Any import pandas as pd from malevich.square import DF, Context, processor from ..lib.chat import exec_chat @processor() async def prompt_completion(variables: DF[Any], ctx: Context): """Use Chat Completions feature from OpenAI Chat completions enable you to chat with OpenAI using a prompt template Available models: https://platform.openai.com/docs/models To use the model you should set the following parameters: - `openai_api_key`: Your OpenAI API key. Get it here: https://platform.openai.com/api-keys - `user_prompt`: The prompt for the user Scroll down to see the full list of parameters. Inputs: A dataframe with variables to be used in the prompts. Each row of the dataframe will be used to generate a prompt. For example, if your prompt contains a name enclosed in {} like this: Hi! Write a story about {someone} You have to have a column `someone` in the input dataframe. For each of such variables you should have a separate column. Outputs: A dataframe with following columns: - content (str): the content of the model response Configuration: - openai_api_key (str, required): your OpenAI API key - user_prompt (str, required): the prompt for the user - system_prompt (str, optional): the prompt for the system - model (str, default: 'gpt-3.5-turbo'): the model to use - organization (str, default: None): the organization to use - max_retries (int, default: 3): the maximum number of retries - temperature (float, default: 0.9): the temperature - max_tokens (int, default: 150): the maximum number of tokens - top_p (float, default: 1.0): the top p - frequency_penalty (float, default: 0.0): the frequency penalty - presence_penalty (float, default: 0.0): the presence penalty - stop (list, default: []]): the stop tokens - stream (bool, default: False): whether to stream the response - n (int, default: 1): the number of completions to generate - response_format (str, default: None): the response format Notes: If `response_format` is set to 'json_object', the system prompt should contain an instruction to return a JSON object, e.g.: ``` You are a creative writer. You are writing a story about {names}. You should mention {colors} in your story. JSON: ``` JSON completion only works with Davinci models Args: variables (DF[Any]): the variables to use in the prompts ctx (Context): the context Returns: DF[Any]: the chat messages """ try: conf = ctx.app_cfg["conf"] except KeyError: raise Exception("OpenAI client not initialized.") assert "user_prompt" in ctx.app_cfg, "Missing `user_prompt` in app config." system_prompt = ctx.app_cfg.get("system_prompt", "") user_prompt = ctx.app_cfg["user_prompt"] messages = [ [ {"role": "system", "content": system_prompt.format(**_vars)}, {"role": "user", "content": user_prompt.format(**_vars)}, ] for _vars in variables.to_dict(orient="records") ] response = await asyncio.gather(*[exec_chat(x, conf) for x in messages]) df = { "content": [], } for _response in response: for _message in _response: df["content"].append(_message.content) return pd.DataFrame(df)
[ "user_prompt", "[]", "system_prompt" ]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~lib~whisper.py
from typing import List from openai import AsyncOpenAI from openai.types.audio import Transcription from ..models.configuration.base import Configuration async def exec_whisper( conf: Configuration, file: str, prompt: str = None, ) -> List[Transcription]: client = AsyncOpenAI( api_key=conf.api_key, max_retries=conf.max_retries, organization=conf.organization ) response: str = await client.audio.transcriptions.create( file=open(file, 'rb'), model='whisper-1', language=conf.language, response_format='text', prompt=prompt, temperature=conf.temperature, ) return response
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~chat_structured.py
import asyncio from collections import defaultdict from typing import Any import pandas as pd from langchain.output_parsers import ResponseSchema from malevich.square import DF, Context, processor from ..lib.broadcast import broadcast from ..lib.chat import exec_structured_chat @processor(id="structured_prompt_completion") async def structured_prompt_completion(variables: DF[Any], ctx: Context): """Use Chat Completions feature from OpenAI Chat completions enable you to chat with OpenAI using a prompt template. This processor assures the output to follow a certain schema Available models: https://platform.openai.com/docs/models To use the model you should set the following parameters: - `openai_api_key`: Your OpenAI API key. Get it here: https://platform.openai.com/api-keys - `user_prompt`: The prompt for the user Scroll down to see the full list of parameters. Inputs: A dataframe with variables to be used in the prompts. Each row of the dataframe will be used to generate a prompt. For example, if your prompt contains a name enclosed in {} like this: Hi! Write a story about {someone} You have to have a column `someone` in the input dataframe. For each of such variables you should have a separate column. Outputs: A dataframe with following column: - index (int): the index of the variable. If `include_index` is set to True, the index will be included in the output, otherwise it will be omitted. - content (str): the content of the model response Configuration: - openai_api_key (str, required): your OpenAI API key - user_prompt (str, required): the prompt for the user - model (str, default: 'gpt-3.5-turbo'): the model to use - organization (str, default: None): the organization to use - max_retries (int, default: 3): the maximum number of retries - temperature (float, default: 0.9): the temperature - max_tokens (int, default: 150): the maximum number of tokens - top_p (float, default: 1.0): the top p - frequency_penalty (float, default: 0.0): the frequency penalty - presence_penalty (float, default: 0.0): the presence penalty - stop (list, default: []]): the stop tokens - stream (bool, default: False): whether to stream the response - n (int, default: 1): the number of completions to generate - response_format (str, default: None): the response format - fields (list of dict, default: empty): a list of fields to parse the output. Each field is a dict that contains fields `name`, `description` and `type` - include_index (bool, default: False): whether to include the index in the output Notes: If `response_format` is set to 'json_object', the system prompt should contain an instruction to return a JSON object, e.g.: ``` You are a creative writer. You are writing a story about {names}. You should mention {colors} in your story. JSON: ``` JSON completion only works with Davinci models Examples: user_prompt: "Write a search queries to find {something} on the Internet" fields: [ {"name": "query", "description": "Google search query", "type": "List[string]"}, {"name": "description", "description": "Summary of your result", "type": "string"} ] If you have the config like above, you have to expect the following output: | index | query | description | | ----- | ---------- | ----------- | | 0 | query_1 | summary | | 0 | query_2 | summary | You will see repeated index and values if some of the variables are lists and others are not. This is because the output is a cartesian product of all the variables. Args: variables (DF[Any]): the variables to use in the prompts ctx (Context): the context Returns: DF[Any]: the chat messages """ # noqa: E501 try: conf = ctx.app_cfg["conf"] except KeyError: raise Exception("OpenAI client not initialized.") assert "user_prompt" in ctx.app_cfg, "Missing `user_prompt` in app config." # system_prompt = ctx.app_cfg.get('system_prompt', '') user_prompt = ctx.app_cfg["user_prompt"] messages = [ user_prompt.format(**_vars) for _vars in variables.to_dict(orient="records") ] schema = [ ResponseSchema( name=field["name"], description=field["description"], type=field.get("type", "string"), ) for field in ctx.app_cfg.get("fields", [{}]) ] response = await asyncio.gather( *[exec_structured_chat(message, conf, schema) for message in messages] ) df = defaultdict(lambda: []) for i, message in enumerate(response): ln = 0 for key, value in broadcast(message).items(): df[key].extend(value) ln = len(value) if conf.include_index: df["index"].extend([variables.index[i]] * ln) return pd.DataFrame(df)
[ "user_prompt" ]
2024-01-10
MalevichAI/malevich-library
lib~src~langchain~apps~init.py
from malevich.square import Context, init from .ops import LangchainOps @init(prepare=True) def initialize_langchain(ctx: Context): """Initialize the langchain app. Initializes two objects: - Embedder (ctx.app_cfg["embedder"]) - used for embeddings - Chat (ctx.app_cfg["chat"]) - used for chat """ ctx.common = LangchainOps() ctx.common.attach_chat_model( backend=ctx.app_cfg.get("chat_backend", "openai"), api_key=ctx.app_cfg.get("api_key", None), temperature=ctx.app_cfg.get("temperature", 0.5), ) ctx.common.attach_embedder( backend=ctx.app_cfg.get("embeddings_backend", "openai"), embeddings_type=ctx.app_cfg.get("embeddings_type", "symmetric"), model_name=ctx.app_cfg.get("model_name", None), api_key=ctx.app_cfg.get("api_key", None), )
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~text_to_speech.py
import asyncio import os import shutil from typing import Any import pandas as pd from malevich.square import APP_DIR, DF, Context, processor from ..lib.tts import exec_tts @processor() async def text_to_speech(variables: DF[Any], ctx: Context): """Use Text-to-Speech feature from OpenAI Produce quality audio from text using OpenAI API To use the model you should set the following parameters: - `openai_api_key`: Your OpenAI API key. Get it here: https://platform.openai.com/api-keys Scroll down to see the full list of parameters. Inputs: A dataframe with a single column `text` containing the text to be converted to speech Outputs: A dataframe with following columns: - filename (str): a key of shared .mp3 files for each input Configuration: - openai_api_key (str, required): your OpenAI API key - model (str, default: 'tts-1'): the model to use - voice (str, default: 'alloy'): the voice to use. One of 'alloy', 'echo', 'fable', 'onyx', 'nova', and 'shimmer' Args: variables (DF[Any]): the variables to use in the prompts ctx (Context): the context Returns: DF[Any]: the chat messages """ try: conf = ctx.app_cfg["conf"] except KeyError: raise Exception("OpenAI client not initialized.") files = [f"voice_{i}_{ctx.run_id}.mp3" for i in range(len(variables))] await asyncio.gather(*[exec_tts(x, conf, f) for x, f in zip( variables.text.to_list(), files )]) for f in files: shutil.move(f, os.path.join(APP_DIR, f)) ctx.share(f) ctx.synchronize([f]) return pd.DataFrame({"filename": files})
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~lib~tts.py
from typing import List from openai import AsyncOpenAI from ..models.configuration.base import Configuration async def exec_tts( inputs: str, conf: Configuration, file: str, ) -> List[str]: client = AsyncOpenAI( api_key=conf.api_key, max_retries=conf.max_retries, organization=conf.organization ) response = await client.audio.speech.create( input=inputs, model=conf.model or 'tts-1', voice=conf.voice, response_format='mp3', speed=conf.speed ) response.stream_to_file(file) return file
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~vision.py
import asyncio import os from typing import Any import pandas as pd from malevich.square import DF, Context, processor from ..lib.vision import exec_vision from ..models.configuration.base import Configuration @processor() async def completion_with_vision(variables: DF[Any], ctx: Context): """Use Language Model with Vision feature from OpenAI Completion with Vision enables you to generate text based on an image. The model is set to 'gpt-4-vision-preview' by default. Configuration: - openai_api_key (str, required): your OpenAI API key - user_prompt (str, required): the prompt for the user - image_column (str, default: 'images'): the column with images - max_tokens (int, default: 2048): the maximum number of tokens - top_p (float, default: 1.0): the probability of the model returning a next token that is in the top P tokens - temperature (float, default: 1.0): the higher the value, the more random the generated text - frequency_penalty (float, default: 0.0): the higher the value, the less likely the model is to repeat the same word - presence_penalty (float, default: 0.0): the higher the value, the less likely the model is to talk about the same topic again - model (str, default: 'gpt-4-vision-preview'): the model to use Inputs: A dataframe with variables to be used in the prompts and an extra column with images files or urls. A column {image_column} should contain either a path to the image file or a url to the image. Each row of the dataframe will be used to generate a prompt. For example, if your prompt contains a name enclosed in {} like this: Hi! Write a story about {someone} You have to have a column `someone` in the input dataframe. For each of such variables you should have a separate column. Outputs: A dataframe with following columns: - content (str): the content of the model response Supported file types: - png - jpg - jpeg - gif - bmp - tiff - tif - webp Args: variables (DF[Any]): a dataframe with variables ctx (Context): context Returns: A dataframe with model responses """ image_column = ctx.app_cfg.get("image_column", "images") assert image_column in variables.columns, f"Missing `{image_column}` column." try: conf: Configuration = ctx.app_cfg["conf"] except KeyError: raise Exception("OpenAI client not initialized.") if not conf.model: conf.model = "gpt-4-vision-preview" assert "user_prompt" in ctx.app_cfg, "Missing `user_prompt` in app config." system_prompt = ctx.app_cfg.get("system_prompt", "") user_prompt = ctx.app_cfg["user_prompt"] def __is_file(x) -> bool: return os.path.isfile( ctx.get_share_path(x, not_exist_ok=True) ) or os.path.isfile(x) messages = [ [ { "role": "system", "content": system_prompt.format(**_vars) }, { "role": "user", "content": user_prompt.format(**_vars)}, ] for _vars in variables.to_dict(orient="records") ] images = variables[image_column].tolist() for i in range(len(images)): if __is_file(images[i]): images[i] = ctx.get_share_path(images[i]) response = await asyncio.gather( *[exec_vision(msgs, image, conf, not __is_file(image)) for msgs, image in zip(messages, images)] ) df = { "content": [], } for _response in response: for _message in _response: df["content"].append(_message.content) return pd.DataFrame(df)
[ "user_prompt", "[]", "system_prompt" ]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~speech_to_text.py
import asyncio import os import shutil import uuid from typing import Any import pandas as pd from malevich.square import DF, Context, processor from ..lib.whisper import exec_whisper @processor() async def speech_to_text(variables: DF[Any], ctx: Context): """Use Speech-to-Text feature from OpenAI Transcribe audio to text using OpenAI API To use the model you should set the following parameters: - `openai_api_key`: Your OpenAI API key. Get it here: https://platform.openai.com/api-keys Scroll down to see the full list of parameters. Inputs: A dataframe with a single column `filename` containing keys to shared audio files Outputs: A dataframe with following columns: - content (str): audio transcription Configuration: - openai_api_key (str, required): your OpenAI API key - language (str, default: 'en'): the language to transcribe audio to - temperature (float, default: 0.9): the temperature - prompt (str, default: None): a short optional prompt to guide the model Args: variables (DF[Any]): the variables to use in the prompts ctx (Context): the context Returns: DF[Any]: the chat messages """ try: conf = ctx.app_cfg["conf"] except KeyError: raise Exception("OpenAI client not initialized.") files = [] for f in variables.filename.to_list(): if not os.path.exists(ctx.get_share_path(f)): raise Exception(f"File {f} does not exist.") _f = uuid.uuid4().hex _ext = os.path.splitext(f)[1] _f = f'{_f}{_ext}' shutil.copy(ctx.get_share_path(f), _f) files.append(_f) p = [ctx.app_cfg.get("prompt", None)] * len(variables) response = await asyncio.gather( *[exec_whisper(conf, f, p_) for f, p_ in zip(files,p) ]) return pd.DataFrame(response, columns=["content"])
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~lib~vision.py
import base64 import os from typing import List from openai import AsyncOpenAI from openai.types.chat import ChatCompletion, ChatCompletionMessage from ..models.configuration.base import Configuration def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') async def exec_vision( messages: List[dict[str, str]], inputs: str, conf: Configuration, is_link: bool = False ) -> List[ChatCompletionMessage]: ext_to_mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.bmp': 'image/bmp', '.tiff': 'image/tiff', '.tif': 'image/tiff', '.webp': 'image/webp', } if not is_link: image_type = os.path.splitext(inputs)[1] assert image_type in ext_to_mime, f'Unsupported image type: {image_type}' image_type = ext_to_mime[image_type] image_content = { 'type': 'image_url', 'image_url': { "url": f"data:image/{image_type};base64,{encode_image(inputs)}" if not is_link else inputs } } for i in range(len(messages)): if messages[i]['role'] == 'user': content = [ { 'type': 'text', 'text': messages[i]['content'] }, image_content ] messages[i]['content'] = content client = AsyncOpenAI( api_key=conf.api_key, max_retries=conf.max_retries, organization=conf.organization ) response: ChatCompletion = await client.chat.completions.create( messages=messages, model=conf.model or 'gpt-4-vision-preview', max_tokens=conf.max_tokens, top_p=conf.top_p, frequency_penalty=conf.frequency_penalty, presence_penalty=conf.presence_penalty, temperature=conf.temperature, ) return [choice.message for choice in response.choices]
[]
2024-01-10
MalevichAI/malevich-library
lib~src~openai_api~apps~text_to_image.py
import asyncio import os import uuid from typing import Any import pandas as pd import requests from malevich.square import APP_DIR, DF, Context, processor from ..lib.image import exec_image @processor() async def text_to_image( variables: DF[Any], ctx: Context ): """Use Text to Image feature from OpenAI Text to Image enables you to generate images from text prompts. To use this processor you should set the following parameters: - `openai_api_key`: Your OpenAI API key. Get it here: https://platform.openai.com/api-keys - `user_prompt`: The prompt for the user Inputs: A dataframe with variables to be used in the prompts. Each row of the dataframe will be used to generate a prompt. For example, if your prompt contains a name enclosed in {} like this: Hi! Write a story about {someone} You have to have a column `someone` in the input dataframe. For each of such variables you should have a separate column. Outputs: The format of the output depends on the configuration. If `download` set to true, then an output dataframe will contain a column `filename` with filenames of downloaded images. Otherwise, an output dataframe will contain a column `link` with links to the images provided directly by Open AI. Configuration: - openai_api_key (str, required): your OpenAI API key - user_prompt (str, required): the prompt for the user - model (str, default: 'dall-e-3'): the model to use - download (bool, default: false): whether to download images - n (int, default: 1): amount of images to generate for each request Args: variables (DF[ImageLinks]): Dataframe with variables for the prompt ctx (Context): Context object Returns: Dataframe with links to images """ download = ctx.app_cfg.get('download', False) try: conf = ctx.app_cfg['conf'] except KeyError: raise Exception( "OpenAI client not initialized." ) user_prompt = ctx.app_cfg.get('user_prompt') inputs = [ user_prompt.format(**__vars) for __vars in variables.to_dict(orient='records') ] _outputs = await asyncio.gather( *[exec_image(x, conf) for x in inputs], ) outputs = [] for _o in _outputs: outputs.extend([x.url for x in _o.data]) if download: files = [] for link in outputs: response = requests.get(link) fname = uuid.uuid4().hex[:8] with open(os.path.join(APP_DIR, fname), 'wb+') as f: f.write(response.content) ctx.share(fname) files.append(fname) ctx.synchronize(files) return pd.DataFrame({ 'file': files }) return pd.DataFrame({ 'link': outputs })
[ "user_prompt" ]
2024-01-10
MalevichAI/malevich-library
lib~src~langchain~apps~functions~df_prompt_format.py
import concurrent.futures import pandas as pd from langchain.chat_models.base import BaseChatModel from langchain.schema import HumanMessage def df_prompt_format( df: pd.DataFrame, prompt_template: str, chat: BaseChatModel ) -> pd.DataFrame: def process_data(data: dict) -> str: message = HumanMessage(content=prompt_template.format(**data)) content = chat([message]).content return content with concurrent.futures.ThreadPoolExecutor() as executor: results = list(executor.map(process_data, df.to_dict('records'))) return pd.DataFrame({"result": results})
[]