python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
import re import os import sympy import pandas as pd from tasks.base import Task, DATA_PATH from prompts.game24 import * def get_current_numbers(y: str) -> str: last_line = y.strip().split('\n')[-1] return last_line.split('left: ')[-1].split(')')[0] class Game24Task(Task): """ Input (x) : a strin...
tree-of-thoughts-main
experiements/tree-of-thought-llm/tasks/game24.py
import os import re from tasks.base import Task, DATA_PATH from prompts.text import * from models import gpt class TextTask(Task): """ Input (x) : a text instruction Output (y) : a text generation Reward (r) : # TODO Input Example: Output Example: """ def __init__(self, file='dat...
tree-of-thoughts-main
experiements/tree-of-thought-llm/tasks/text.py
import re import json from tasks.base import Task from prompts.crosswords import * from models import gpt class MiniCrosswordsEnv: def __init__(self, file='mini0505.json'): self.file = f'data/crosswords/{file}' self.file = json.load(open(self.file)) self.n = len(self.file) self.cac...
tree-of-thoughts-main
experiements/tree-of-thought-llm/tasks/crosswords.py
DATA_PATH = './data' class Task: def __init__(self): pass def __len__(self) -> int: pass def get_input(self, idx: int) -> str: pass def test_output(self, idx: int, output: str): pass
tree-of-thoughts-main
experiements/tree-of-thought-llm/tasks/base.py
# 5-shot standard_prompt = '''Use numbers and basic arithmetic operations (+ - * /) to obtain 24. Input: 4 4 6 8 Answer: (4 + 8) * (6 - 4) = 24 Input: 2 9 10 12 Answer: 2 * 12 * (10 - 9) = 24 Input: 4 9 10 13 Answer: (13 - 9) * (10 - 4) = 24 Input: 1 4 8 8 Answer: (8 / 4 + 1) * 8 = 24 Input: 5 5 5 9 Answer: 5 + 5 + 5 +...
tree-of-thoughts-main
experiements/tree-of-thought-llm/prompts/game24.py
standard_prompt = ''' Write a coherent passage of 4 short paragraphs. The end sentence of each paragraph must be: {input} ''' cot_prompt = ''' Write a coherent passage of 4 short paragraphs. The end sentence of each paragraph must be: {input} Make a plan then write. Your output should be of the following format: Pla...
tree-of-thoughts-main
experiements/tree-of-thought-llm/prompts/text.py
# 5 shot standard_prompt = ''' Solve 5x5 mini crosswords. Given an input of 5 horizontal clues and 5 vertical clues, generate an output of 5 rows, where each row is 5 letter separated by space. Input: h1. A lunar valley h2. A fatty oil h3. To entice h4. To lower; to reduce h5. A solitary person v1. According to the ro...
tree-of-thoughts-main
experiements/tree-of-thought-llm/prompts/crosswords.py
tree-of-thoughts-main
experiements/extremely_experimental/reinforcement/v1.py
#give topic [What are quantum field theorem proofs respond in math notation] -> 100 questions by external model -> tree of thoughts for each question #give dataset -> ask questions about each example and fine tune on like alpaca dataset import json from tree_of_thoughts.treeofthoughts import OptimizedTreeofThoughts fro...
tree-of-thoughts-main
experiements/extremely_experimental/generate_dataset/main.py
from abc import abstractmethod, ABC from langchain import OpenAI from langchain.agents import initialize_agent from langchain.agents import AgentType class AbstractLanguageModel(ABC): @abstractmethod def generate_thoughts(self, state, k): pass @abstractmethod def evaluate_states(self, states...
tree-of-thoughts-main
experiements/extremely_experimental/prompting/LangChain_model.py
import concurrent.futures from abc import ABC, abstractmethod import openai import os import guidance import time class AbstractLanguageModel(ABC): @abstractmethod def generate_thoughts(self, state, k): pass @abstractmethod def evaluate_states(self, states): pass class CustomLanguag...
tree-of-thoughts-main
experiements/extremely_experimental/prompting/guidancePrompt.py
from tree_of_thoughts.models.openai_models import OpenAILanguageModel from tree_of_thoughts.treeofthoughts import TreeofThoughtsDFS # api_model= "gpt-3.5-turbo" model = OpenAILanguageModel(api_key='api key', api_model=api_model) #choose search algorithm('BFS' or 'DFS') search_algorithm = "BFS" # value or vote eva...
tree-of-thoughts-main
examples/example_totdfs.py
from tree_of_thoughts.models.openai_models import OpenAILanguageModel from tree_of_thoughts.treeofthoughts import MonteCarloTreeofThoughts api_model= "gpt-3.5-turbo" model = OpenAILanguageModel(api_key='api key', api_model=api_model) # Initialize the MonteCarloTreeofThoughts class with the model tree_of_thoughts ...
tree-of-thoughts-main
examples/montecarlo_example.py
from tree_of_thoughts.treeofthoughts import TreeofThoughts, HuggingLanguageModel, MonteCarloTreeofThoughts model_name="gpt" model = HuggingLanguageModel(model_name, model_tokenizer=model_name, verbose=True) # Initialize the Mon...
tree-of-thoughts-main
examples/huggingface_example.py
from tree_of_thoughts.models.openai_models import OpenAILanguageModel from tree_of_thoughts.treeofthoughts import TreeofThoughts2 # api_model= "gpt-3.5-turbo" model = OpenAILanguageModel(api_key='api key', api_model=api_model) tree_of_thoughts= TreeofThoughts2(model) #search_algorithm) # Note to reproduce the s...
tree-of-thoughts-main
examples/example_tot2.py
from tree_of_thoughts.models.openai_models import OpenAILanguageModel from tree_of_thoughts.treeofthoughts import TreeofThoughtsASearch # api_model= "gpt-4" model = OpenAILanguageModel(api_key='api key', api_model=api_model) tree_of_thoughts= TreeofThoughtsASearch(model) #search_algorithm) # Note to reproduce t...
tree-of-thoughts-main
examples/example_totA.py
from tree_of_thoughts.treeofthoughts import HFPipelineModel, MonteCarloTreeofThoughts model_name="gpt2" gpt2_pipeline_model = HFPipelineModel(model_name) tree_of_thoughts = MonteCarloTreeofThoughts(gpt2_pipeline_model) # initial_prompt = """ Input: 2 8 8 14 Possible next steps: 2 + 8 = 10 (left: 8 10 14) 8 / ...
tree-of-thoughts-main
examples/pipelinehuggingface.py
#thought -> evaluated value (0.4, This solution is invalid because x) -> thought prompt + this solution is invalid because + better eval import json import os import time DATA_PATH = './data' import logging import concurrent.futures from queue import PriorityQueue from typing import Any, Dict, Union import numpy a...
tree-of-thoughts-main
tree_of_thoughts/treeofthoughts.py
from tree_of_thoughts.models.openai_models import OpenAILanguageModel, OptimizedOpenAILanguageModel from tree_of_thoughts.treeofthoughts import TreeofThoughts, MonteCarloTreeofThoughts, TreeofThoughtsBFS, TreeofThoughtsDFS, TreeofThoughtsBEST, TreeofThoughtsASearch from tree_of_thoughts.models.abstract_language_model i...
tree-of-thoughts-main
tree_of_thoughts/__init__.py
from typing import List, Mapping, Union, Any, Callable from typing import Dict import requests from copy import deepcopy from dataclasses import dataclass def _default_extractor(json_response: Dict[str, Any], stop_parameter_name) -> str: """ This function extracts the response from the JSON object using the d...
tree-of-thoughts-main
tree_of_thoughts/text_generation_web_ui.py
import re from typing import Any, Callable, Optional, Tuple, Union from langchain.llms import OpenAI from langchain_experimental.tot.checker import ToTChecker from langchain_experimental.tot.thought import ThoughtValidity class LangchainTOT: def __init__(self, problem_description: Optional[str]...
tree-of-thoughts-main
tree_of_thoughts/langchain_tot.py
tree-of-thoughts-main
tree_of_thoughts/models/__init__.py
import guidance from tree_of_thoughts.models.abstract_language_model import AbstractLanguageModel import time import os import openai class GuidanceLanguageModel(AbstractLanguageModel): def __init__(self, model, strategy="cot", evaluation_strategy="value", enable_ReAct_prompting=False): # gpt4 = guidance....
tree-of-thoughts-main
tree_of_thoughts/models/guidance_model.py
import os import openai import time from tree_of_thoughts.models.abstract_language_model import AbstractLanguageModel import concurrent.futures import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class OpenAILanguageModel(A...
tree-of-thoughts-main
tree_of_thoughts/models/openai_models.py
import requests import os class Anthropic: """Anthropic large language models.""" def __init__(self, model="claude-2", max_tokens_to_sample=256, temperature=None, top_k=None, top_p=None, streaming=False, default_request_timeout=None): self.model = model self.max_tokens_to_sample = max_tokens_t...
tree-of-thoughts-main
tree_of_thoughts/models/anthropic.py
from abc import ABC, abstractmethod class AbstractLanguageModel(ABC): @abstractmethod def generate_thoughts(self, state, k): pass @abstractmethod def evaluate_states(self, states): pass
tree-of-thoughts-main
tree_of_thoughts/models/abstract_language_model.py
from transformers import AutoModelForCausalLM, AutoTokenizer from transformers import pipeline from tree_of_thoughts.models.abstract_language_model import AbstractLanguageModel class HuggingLanguageModel(AbstractLanguageModel): def __init__(self, model_name, model_tokenizer=None, verbose=False): self.mode...
tree-of-thoughts-main
tree_of_thoughts/models/huggingface_model.py
from setuptools import setup, find_packages setup( name = 'omnimorph', packages = find_packages(exclude=[]), version = '0.0.7', license='MIT', description = 'OmniMorph - Pytorch', author = 'Agora', author_email = 'kye@apac.ai', long_description_content_type = 'text/markdown', url = 'https://github.co...
OmniMorph-master
setup.py
import torch import torch.nn as nn class VisionLanguageEmbedding(nn.Module): def __init__(self, text_embed, vision_embed): super().__init__() self.text_embed = text_embed self.vision_embed = vision_embed def forward(self, textual_tokens, visual_tokens, **kwargs): if textual_tok...
OmniMorph-master
OmniMorph.py
import torch import torch.nn as nn import torch.nn.functional as F class VisionLanguageEmbedding(nn.Module): def __init__(self, text_embed, vision_embed): super().__init__() self.text_embed = text_embed self.vision_embed = vision_embed def forward(self, textual_tokens, visual_tokens,...
OmniMorph-master
iterations/OMNI.py
import torch import torch.nn as nn class VisionLanguageEmbedding(nn.Module): def __init__(self, text_embed, vision_embed): super().__init__() self.text_embed = text_embed self.vision_embed = vision_embed def forward(self, textual_tokens, visual_tokens, **kwargs): if textual_tok...
OmniMorph-master
iterations/OMNI4.py
import torch import torch.nn as nn class OmniMorph(nn.Module): def __init__(self, *args, **kwargs): super().__init__() self._embedding_registry = {} self._embedding_instances = {} def register_embedding(self, modality_type, embedding_class): self._embedding_registry[modality_...
OmniMorph-master
iterations/OMNI3.py
import torch import torch.nn as nn class VisionLanguageEmbedding(nn.Module): def __init__(self, text_embed, vision_embed): super().__init__() self.text_embed = text_embed self.vision_embed = vision_embed def forward(self, textual_tokens, visual_tokens, **kwargs): if textual_...
OmniMorph-master
iterations/OMNI2.py
from setuptools import setup, find_packages setup( name = 'blockwise-parallel-transformer', packages = find_packages(exclude=[]), version = '0.1.2', license='MIT', description = '32x Faster Attentionn', author = 'Kye Gomez', author_email = 'kye@apac.ai', long_description_content_type = 'text/markdown',...
Blockwise-Parallel-Transformer-main
setup.py
from jax import random from blockwise_parallel import BlockwiseParallelTransformerAttention from torch.nn import Embedding #hyperparams input_size = 512 num_heads = 8 hidden_size = 512 num_layers = 6 max_seq_len = 1024 block_size = 64 #create random input sequence key = random.PRNGKey(0) x = random.normal(key, (1, m...
Blockwise-Parallel-Transformer-main
example.py
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/__init__.py
# coding=utf-8 # Copyright 2021 The EleutherAI and 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 requi...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/model.py
import dataclasses import pprint from functools import partial import re from tqdm import tqdm, trange import numpy as np import bpt.tools.utils as utils import jax import jax.numpy as jnp from jax.experimental.pjit import pjit from jax.sharding import PartitionSpec as PS import flax from flax import linen as nn from...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/train.py
import dataclasses import pprint import time from functools import partial import json from multiprocessing import Pool import h5py import bpt.tools.utils as utils from ml_collections.config_dict import config_dict from ml_collections import ConfigDict from tqdm import tqdm, trange import numpy as np from datasets im...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/data.py
import functools import json import math from functools import partial from typing import Optional, Tuple import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from einops import rearrange from flax.linen import combine_masks, make_causal_mask from jax import lax from jax import numpy as jnp ...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/blocks/vanilla.py
import functools import json import math from functools import partial from typing import Callable, NamedTuple, Optional import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from einops import rearrange from flax.linen import combine_masks, make_causal_mask from jax import lax from jax import ...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/blocks/blockwise_parallel_v1.py
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/blocks/__init__.py
import functools import json import math from functools import partial from typing import Callable, NamedTuple, Optional import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from einops import rearrange from flax.linen import combine_masks, make_causal_mask from jax import lax from jax import ...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/blocks/blockwise_parallel.py
import functools import json import math from functools import partial from typing import Callable, NamedTuple, Optional import flax.linen as nn import jax import jax.numpy as jnp import numpy as np from einops import rearrange from flax.linen import combine_masks, make_causal_mask from jax import lax from jax import ...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/blocks/memeff.py
import os import numpy as np from ml_collections import ConfigDict import bpt.tools.utils as utils import jax import jax.numpy as jnp import flax from flax.serialization import ( from_bytes, to_bytes, to_state_dict, from_state_dict ) from flax.traverse_util import flatten_dict, unflatten_dict, empty_node import msg...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/tools/checkpoint.py
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/tools/__init__.py
import os import math from typing import Any, Mapping, Text, Tuple, Union, NamedTuple from functools import partial import re import dataclasses import random import dill import flax import jax import jax.numpy as jnp from jax.sharding import PartitionSpec as PS from jax.sharding import Mesh from jax.experimental.pjit...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/tools/jax_utils.py
import os import time from typing import Any, Mapping, Text, Tuple, Union, NamedTuple from functools import partial import re import dataclasses import random from ml_collections.config_dict import config_dict from ml_collections import ConfigDict import jax import jax.numpy as jnp import numpy as np from absl import ...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/tools/optimizers.py
import inspect import logging import os import pprint import random import tempfile import time import uuid from concurrent.futures import ThreadPoolExecutor from copy import copy from io import BytesIO from socket import gethostname import dataclasses import absl.flags import absl.logging import cloudpickle as pickle...
Blockwise-Parallel-Transformer-main
blockwise-parallel-transformer/bpt/tools/utils.py
import torch import torch.nn as nn class BlockwiseParallelTransformerAttention(nn.Module): def __init__(self, input_size, num_heads, hidden_size, num_layers, max_seq_len, block_size): super(BlockwiseParallelTransformerAttention, self).__init__() self.input_size = input_size self.num_heads ...
Blockwise-Parallel-Transformer-main
blockwise_parallel/blockwise_parallel_torch.py
import torch import torch.nn as nn class BlockwiseParallelTransformer(nn.Module): def __init__(self, input_dim, output_dim, head_dim, num_heads, num_query_blocks, num_kv_blocks): super(BlockwiseParallelTransformer, self).__init__() self.query_blocks = num_query_blocks self.kv_blocks = num_k...
Blockwise-Parallel-Transformer-main
blockwise_parallel/test1.py
# from blockwise_parallel.blockwise_paralle import BlockwiseParallelTransformerAttention # from blockwise_parallel.test1 import BlockwiseParallelTransformer/ from blockwise_parallel.blockwise_parallel_jax import BlockwiseParallelTransformerAttention
Blockwise-Parallel-Transformer-main
blockwise_parallel/__init__.py
# import jax # import jax.numpy as jnp # from jax import nn, lax # from jax.experimental.stax import Dense # class BlockwiseParallelTransformerAttention: # def __init__(self, input_size, num_heads, hidden_size, num_layers, max_seq_len, block_size): # self.input_size = input_size # self.num_heads = ...
Blockwise-Parallel-Transformer-main
blockwise_parallel/blockwise_parallel_jax.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from einops import rearrange from types import partial def quick_gelu(x): return x * torch.sigmoid(1.702 * x) ACT2FN = { "gelu": F.gelu, "relu": F.relu, "silu": F.silu, "swish": F.swish, "gelu_new": quick_...
Blockwise-Parallel-Transformer-main
blockwise_parallel/blockwise_torch.py
import torch import numpy #prexisting arrays w = torch.tensor([1, 2, 3]) #tuple w = torch.tensor((1, 2, 3)) # numpy array w = torch.tensor(numpy.array([1, 2, 3])) #init by sized w = torch.empty(100, 200) #not initialized w = torch.zeros(100, 200) # elements with 0.0 w = torch.ones(100, 200) # elements with 1.0 #...
TorchPractice-main
TorchPractice/tensors.py
TorchPractice-main
TorchPractice/__init__.py
from setuptools import setup, find_packages setup( name = 'optimus-prime-transformers', packages = find_packages(exclude=['examples']), version = '1.2.1', license='MIT', description = 'optimus-prime - Pytorch', author = 'Kye Gomez', author_email = 'kye@apac.ai', url = 'https://github.com/kyegomez/Optim...
Optimus-Prime-main
setup.py
import gzip import tqdm import torch import random import numpy as np from torch.utils.data import Dataset, DataLoader from optimus_prime import TransformerWrapper, Decoder, AutoregressiveWrapper, AndromedaEmbedding # constants NUM_BATCHES = int(1e5) BATCH_SIZE = 4 GRADIENT_ACCUMULATE_EVERY = 1 LEARNING_RATE = 1e-...
Optimus-Prime-main
train.py
import torch from optimus_prime.attend import Attend model = Attend(dim=512, dim_head=64, heads=64, q_bucket_size=128, k_bucket_size=128, parallel=False, mixed_precision=False, Flash2=True) q = torch.randn(1, 8, 512, 64) k = torch.randn(1, 8, 512, 64) v = torch.randn(1, 8, 512, 64) out, _ = model(q, k, v) assert out....
Optimus-Prime-main
simple.py
import torch from torch import nn import torch.nn.functional as F from einops import rearrange, pack, unpack from optimus_prime.autoregressive_wrapper import top_k, eval_decorator # helper functions def exists(val): return val is not None def divisible_by(numer, denom): return (numer % denom) == 0 # xl a...
Optimus-Prime-main
optimus_prime/xl_autoregressive_wrapper.py
from math import ceil import torch from torch import nn import torch.nn.functional as F from einops import rearrange, pack, unpack def exists(val): return val is not None def eval_decorator(fn): def inner(self, *args, **kwargs): was_training = self.training self.eval() out = fn(self, ...
Optimus-Prime-main
optimus_prime/autoregressive_wrapper.py
#add ability to choose your own tokenizer, and embedder, and ask what else can be done for production level training import math from random import random import torch from torch import nn, einsum, Tensor import torch.nn.functional as F from functools import partial, wraps from inspect import isfunction from datacl...
Optimus-Prime-main
optimus_prime/x_transformers.py
import torch from packaging import version if version.parse(torch.__version__) >= version.parse('2.0.0'): from einops._torch_specific import allow_ops_in_compiled_graph allow_ops_in_compiled_graph() from x_transformers.x_transformers import XTransformer, Encoder, Decoder, CrossAttender, Attention, Transforme...
Optimus-Prime-main
optimus_prime/__init__.py
import torch from torch import nn import torch.nn.functional as F def exists(val): return val is not None class ContinuousAutoregressiveWrapper(nn.Module): def __init__(self, net, ignore_index = -100, pad_value = 0): super().__init__() self.net = net self.max_seq_len = net.max_seq_len ...
Optimus-Prime-main
optimus_prime/continuous_autoregressive_wrapper.py
from functools import partial import torch from torch import nn, einsum, Tensor import torch.nn.functional as F from collections import namedtuple from functools import wraps from packaging import version from dataclasses import dataclass from einops import rearrange from optimus_prime.flash import FlashAttention #...
Optimus-Prime-main
optimus_prime/attend.py
import math import torch from torch import nn, einsum from torch.autograd.function import Function from einops import rearrange from torch.cuda.amp import autocast, GradScaler from torch.nn import DataParallel # constants EPSILON = 1e-10 # helper functions def exists(val): return val is not None def default(...
Optimus-Prime-main
optimus_prime/flash.py
import math from random import random from contextlib import nullcontext from collections import namedtuple import torch import torch.nn.functional as F from torch import nn from einops import rearrange from optimus_prime.x_transformers import TransformerWrapper from typing import Optional # constants Losses = na...
Optimus-Prime-main
optimus_prime/nonautoregressive_wrapper.py
import logging import pytest import torch from optimus_prime.attend import Attend # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def test_forward_pass(): logger.info("Running forward pass test...") model = Attend(dim=512, dim_head=64, q_bucket_size=128, k_bucket_...
Optimus-Prime-main
tests/attend/attend.py
import tqdm import torch import torch.optim as optim from optimus_prime_transformers import XTransformer # constants NUM_BATCHES = int(1e5) BATCH_SIZE = 32 LEARNING_RATE = 3e-4 GENERATE_EVERY = 100 NUM_TOKENS = 16 + 2 ENC_SEQ_LEN = 32 DEC_SEQ_LEN = 64 + 1 # helpers def cycle(): while True: prefix = tor...
Optimus-Prime-main
examples/toy_tasks/enc_dec_copy.py
from optimus_prime_transformers import ( TransformerWrapper, Encoder, NonAutoregressiveWrapper ) import tqdm import gzip import numpy as np import torch import torch.optim as optim from torch.utils.data import DataLoader, Dataset # constants NUM_BATCHES = int(1e8) BATCH_SIZE = 4 GRADIENT_ACCUMULATE_EVERY...
Optimus-Prime-main
examples/enwik8_simple/train_nar.py
from optimus_prime_transformers import TransformerWrapper, Decoder from optimus_prime_transformers.autoregressive_wrapper import AutoregressiveWrapper import random import tqdm import gzip import numpy as np import torch import torch.optim as optim from torch.utils.data import DataLoader, Dataset # constants NUM_BAT...
Optimus-Prime-main
examples/enwik8_simple/train.py
from setuptools import setup, find_packages # setup( name = 'hivemind', packages = find_packages(exclude=[]), version = '0.0.1', license='MIT', description = 'Hive - Pytorch', author = 'Kye Gomez', author_email = 'kye@apac.ai', long_description_content_type = 'text/markdown', url = 'https://github.c...
Hive-main
setup.py
print("hello there 😊 ")
Hive-main
hive/main.py
from logic_guide import LogicGuide, QuoteGuide, AlgebraGuide, MemoryGuide # Example usage: model_id="tiiuae/falcon-40b" logic_guide = LogicGuide(model_id=model_id) #provide few shot prompt for better results text = """ Context: Every dog is small. Every feline is a snake. Every animal is not bitter. Sheep are bitter...
LOGICGUIDE-main
example_huggingface.py
from logic_guide import LogicGuide logic_guide = LogicGuide(openai_api_key='', openai_api_model='gpt4') #provide few shot prompt for better results text = """ Context: Every dog is small. Every feline is a snake. Every animal is not bitter. Sheep are bitter. Cats are carnivores. Each vertebrate is a mammal. Mammals ...
LOGICGUIDE-main
example_openai.py
from setuptools import setup, find_packages setup( name = 'logic_guide', packages = find_packages(exclude=['examples']), version = '0.0.1', license='APACHE', description = 'Logic Guide - HF', author = 'Kye Gomez', author_email = 'kye@apac.ai', url = 'https://github.com/kyegomez/LOGICGUIDE', long_desc...
LOGICGUIDE-main
setup.py
import re # class LogicGuide: # def __init__(self): # self.delimiters = ("t1", "t2") # example delimiters for guiding text extraction # def guide_function(self, generated_sequence): # """Function to define a set of valid generations based on previously generated sequences.""" # # Impl...
LOGICGUIDE-main
logic_guide/logicguide.py
from logic_guide.logicguide import AlgebraGuide, LogicGuide, QuoteGuide, MemoryGuide, FactTool, LogicTool, GuideFunction, DigitGuide, UniversalGuide
LOGICGUIDE-main
logic_guide/__init__.py
import os import openai import time import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) class OpenAILanguageModel: def __init__(self, api_key, api_base="", api_model=""): if api_key == "" or api_key == None: ...
LOGICGUIDE-main
logic_guide/utils/openai.py
from setuptools import setup, find_packages setup( name = 'swarms', packages = find_packages(exclude=[]), version = '1.4.1', license='MIT', description = 'Swarms - Pytorch', author = 'Kye Gomez', author_email = 'kye@apac.ai', long_description_content_type = 'text/markdown', url = 'https://github.com/...
swarms-master
setup.py
from swarms import Worker node = Worker( openai_api_key="", ai_name="Optimus Prime", ) task = "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times." response = node.run(task) print(response)
swarms-master
example.py
from swarms import worker_node # Your OpenAI API key api_key = "sksdsds" # Initialize a WorkerNode with your API key node = worker_node(api_key) # Define an objective objective = "Please make a web GUI for using HTTP API server..." # Run the task task = node.run(objective) print(task)
swarms-master
playground/worker_auto.py
from swarms import WorkerUltraUltraNode # Define an objective objective = """ Please make a web GUI for using HTTP API server. The name of it is Swarms. You can check the server code at ./main.py. The server is served on localhost:8000. Users should be able to write text input as 'query' and url array as 'files', ...
swarms-master
playground/ultranode_example.py
from swarms import HierarchicalSwarm # Retrieve your API key from the environment or replace with your actual key api_key = "sksdsds" # Initialize HierarchicalSwarm with your API key swarm = HierarchicalSwarm(openai_api_key=api_key) # Define an objective objective = """ Please develop and serve a simple web TODO ap...
swarms-master
playground/todo_app.py
from swarms import HierarchicalSwarm # Retrieve your API key from the environment or replace with your actual key api_key = "" # Initialize HierarchicalSwarm with your API key swarm = HierarchicalSwarm(api_key) # Define an objective objective = "Find 20 potential customers for a HierarchicalSwarm based AI Agent auto...
swarms-master
playground/swarms_example.py
import os from swarms.swarms.swarms import WorkerUltra api_key = os.getenv("OPENAI_API_KEY") # Define an objective objective = """ Please make a web GUI for using HTTP API server. The name of it is Swarms. You can check the server code at ./main.py. The server is served on localhost:8000. Users should be able to writ...
swarms-master
playground/worker_ultra.py
swarms-master
playground/DIY.py
from swarms import swarm # Use the function api_key = "APIKEY" objective = "What is the capital of the UK?" result = swarm(api_key, objective) print(result) # Prints: "The capital of the UK is London."
swarms-master
playground/easy_example.py
from swarms import AutoScaler auto_scaler = AutoScaler() auto_scaler.start() for i in range(100): auto_scaler.add_task(f"Task {i}")
swarms-master
playground/autoscaler.py
from swarms.structs.workflow import Workflow workflow = Workflow() workflow.add('Find 50 ceos in linkedin in agriculture ')
swarms-master
playground/workflow.py
from ..swarms import HierarchicalSwarm # Retrieve your API key from the environment or replace with your actual key api_key = "sksdsds" # Initialize HierarchicalSwarm with your API key swarm = HierarchicalSwarm(openai_api_key=api_key) # Define an objective objective = """ Please develop and serve a simple community ...
swarms-master
playground/social_app.py
from swarms import HierarchicalSwarm # Retrieve your API key from the environment or replace with your actual key api_key = "sksdsds" # Initialize HierarchicalSwarm with your API key swarm = HierarchicalSwarm(openai_api_key=api_key) # Define an objective objective = """ Please make a web GUI for using HTTP API serv...
swarms-master
playground/gui_app.py
from swarms import HierarchicalSwarm swarm = HierarchicalSwarm( openai_api_key="key", model_type="openai", model_id="gpt-4", use_vectorstore=False, use_async=False, human_in_the_loop=False, logging_enabled=False ) #run the swarm with an objective result = swarm.run("Design a new car") #...
swarms-master
playground/DIY/hierchical.py
import pytest from unittest.mock import Mock from swarms.swarms.orchestrate import Orchestrator @pytest.fixture def mock_agent(): return Mock() @pytest.fixture def mock_task(): return {"task_id": 1, "task_data": "data"} @pytest.fixture def mock_vector_db(): return Mock() @pytest.fixture def orchestrato...
swarms-master
tests/orchestrate.py
import pytest import logging from unittest.mock import patch from swarms.swarms.swarms import HierarchicalSwarm # replace with your actual module name @pytest.fixture def swarm(): return HierarchicalSwarm( model_id='gpt-4', openai_api_key='some_api_key', use_vectorstore=True, em...
swarms-master
tests/swarms.py
import pytest from unittest.mock import Mock, patch from swarms.agents.agents import AgentNodeInitializer, AgentNode, agent # replace with actual import # For initializing AgentNodeInitializer in multiple tests @pytest.fixture def mock_agent_node_initializer(): with patch('swarms.agents.agents.ChatOpenAI') as moc...
swarms-master
tests/agents/agents.py
import pytest from unittest.mock import Mock from swarms.memory.oceandb import OceanDB @pytest.fixture def mock_ocean_client(): return Mock() @pytest.fixture def mock_collection(): return Mock() @pytest.fixture def ocean_db(mock_ocean_client): OceanDB.client = mock_ocean_client return OceanDB() ...
swarms-master
tests/agents/memory/main.py
import unittest import os from unittest.mock import patch from langchain import HuggingFaceHub, ChatOpenAI from swarms.models.llm import LLM class TestLLM(unittest.TestCase): @patch.object(HuggingFaceHub, '__init__', return_value=None) @patch.object(ChatOpenAI, '__init__', return_value=None) def setUp(sel...
swarms-master
tests/agents/models/LLM.py
import pytest import torch from unittest.mock import Mock from swarms.models.huggingface import HuggingFaceLLM @pytest.fixture def mock_torch(): return Mock() @pytest.fixture def mock_autotokenizer(): return Mock() @pytest.fixture def mock_automodelforcausallm(): return Mock() @pytest.fixture def ...
swarms-master
tests/agents/models/hf.py
import pytest from unittest.mock import MagicMock, patch from swarms.worker.worker_node import WorkerNodeInitializer, WorkerNode # replace your_module with actual module name # Mock Tool for testing class MockTool(Tool): pass # Fixture for llm @pytest.fixture def mock_llm(): return MagicMock() # Fixture fo...
swarms-master
tests/agents/workers/worker_node.py