id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
13,632 | import sys
import os
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms
from torch.utils import data
from d2l import torch as d2l
import d2lutil.common as common
def cross_entropy(y_hat, y):
return - torch.log(y_hat.gather(1, y.view(-1, 1))) | null |
13,633 | import sys
import os
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms
from torch.utils import data
from d2l import torch as d2l
import d2lutil.common as common
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item() | null |
13,634 | import sys
import os
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms
from torch.utils import data
from d2l import torch as d2l
import d2lutil.common as common
d2l.use_svg_display()
y = torch.LongTensor([0, 2])
y_hat.gather(1, y.view(-1, 1))
y_hat, y):
return (y... | null |
13,635 | import sys
import torch
from d2l import torch as d2l
from torch import nn
weight(m
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
def init_weight(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01) | null |
13,636 | import sys
import torch
from d2l import torch as d2l
from torch import nn
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item() | null |
13,637 | import sys
import torch
from d2l import torch as d2l
from torch import nn en(), nn.Linear(784, 10))
for X, y in data_iter:
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, l... | null |
13,638 | import random
import torch
X = torch.normal(0, 1, (nums_example, len(w)))
y = torch.matmul(X, w) + b
print("y_shape:", y.shape)
y += torch.normal(0, 0.01, y.shape) urn X, y.reshape(-1, 1) torch.tensor([2, -3.4])
for X, y in read_data(batch_size, features, labels):
print("X:", X, "\ny", y)
break... | null |
13,639 | import random
import torch
torch.tensor([2, -3.4])
nums_example = len(features)
indices = list(range(nums_example)) s_example, batch_size): # range(start, stop, step)
index_tensor = torch.tensor(indices[i: min(i + batch_size, nums_example)])
yield features[index_tensor], lables[index_tens... | null |
13,640 | import random
import torch
torch.tensor([2, -3.4])
with torch.no_grad(): # with torch.no_grad() 则主要是用于停止autograd模块的工作,
for param in params:
param -= lr * param.grad / batch_size ## 这里用param = param - lr * param.grad / batch_size会导致导数丢失, zero_()函数报错
param.grad.zero_() ## 导数如... | null |
13,641 | import random
import torch
def loss(y_hat, y):
# print("y_hat_shape:",y_hat.shape,"\ny_shape:",y.shape)
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2 # 这里为什么要加 y_hat_shape: torch.Size([10, 1]) y_shape: torch.Size([10]) | null |
13,642 | import random
import torch
torch.tensor([2, -3.4])
with torch.no_grad(): # with torch.no_grad() 则主要是用于停止autograd模块的工作,
for param in params:
param -= lr * param.grad / batch_size ## 这里用param = param - lr * param.grad / batch_size会导致导数丢失, zero_()函数报错
param.grad.zero_() ## 导数如... | null |
13,643 | import torch
import torchvision
import torchvision.transforms as transforms
from d2l import torch as d2l
from torch.utils import data
from torchvision.datasets.mnist import read_image_file, read_label_file
from torchvision.datasets.utils import extract_archive
def hello():
print("semilogy_HELLO") | null |
13,644 | import torch
import torchvision
import torchvision.transforms as transforms
from d2l import torch as d2l
from torch.utils import data
from torchvision.datasets.mnist import read_image_file, read_label_file
from torchvision.datasets.utils import extract_archive
def load_fashion_mnist(batch_size):
extract_archive('D... | null |
13,645 | import os
import torch
from torch import nn
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
()) e) in net[0].named_parameters()]) me, param.shape)
t_normal)
nn.init.xavier_uniform_(m.weight)
it)
nn.ReLU(), nn.Linear(8, 1))
net(X
net[2].weight.data[0, 0] = 100ta[0])
def block2():... | null |
13,646 | import os
import torch
from torch import nn
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.Linear:
... | null |
13,647 | import os
import torch
from torch import nn
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.Linear:
... | null |
13,648 | import os
import torch
from torch import nn
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.Linear:
... | null |
13,649 | import os
import torch
from torch import nn
if type(m) == nn.Linear:
nn.init.normal_(m.weight, mean=0, std=0.01)
nn.init.zeros_(m.bias)
if type(m) == nn.Linear:
nn.init.constant_(m.weight, 1)
nn.init.zeros_(m.bias)
nn.init.xavier_uniform_(m.weight)
if type(m) == nn.Linear:
... | null |
13,650 | import os
import torch
from torch import nn
print(net(X))
print('1.访问第二个全连接层的参数') for name, param in net.named_parameters()])
):
return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU())
print('3.嵌套块的参数')
print(rgnet)
print(rgnet(X))
if type(m) == nn.Linear:
nn.init.normal_(m.weight, ... | null |
13,651 | import torch
print('1.自动梯度计算')
print('y:', y)
print('x.grad:', x.grad)
print('x.grad:', x.grad)
print('2.Python控制流的梯度计算')
def f(a):
b = a * 2
print(b.norm())
while b.norm() < 1000: # 求L2范数:元素平方和的平方根
b = b * 2
if b.sum() > 0:
c = b
else:
c = 100 * b
return c | null |
13,652 | import numpy as np
from d2l import torch as d2l
import os
def f(x):
return 3 * x ** 2 - 4 * x | null |
13,653 | import numpy as np
from d2l import torch as d2l
import os
def numerical_lim(f, x, h):
return (f(x + h) - f(x)) / h | null |
13,654 | import os
import torch
from torch import nn
Y = conv2d(X)
2:])
def comp_conv2d(conv2d, X):
# 这里的(1,1)表示批量大小和通道数都是1
X = X.reshape((1, 1) + X.shape)
Y = conv2d(X)
# 省略前两个维度:批量大小和通道
return Y.reshape(Y.shape[2:]) | null |
13,655 | import os
import torch
from torch import nn
from d2l import torch as d2l
torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
orr2d_multi_in(X, k) for k in K], 0 torch.stack((K, K + 1, K + 2), 0)
torch.normal(0, 1, (3, 3, 3))... | null |
13,656 | import os
import torch
from torch import nn
from d2l import torch as d2l
torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
print(corr2d_multi_in(X, K))
orr2d_multi_in(X, k) for k in K], 0 torch.stack((K, K + 1, K + 2), 0)
print... | null |
13,657 | import os
import torch
from torch import nn
from d2l import torch as d2l
ech.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))n range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = (X[i:i + h, j:j + w] * K).sum() # X是输入矩阵
return Y
Y = Y1.reshape((1, 1, 6, 7))
if (i + 1) % 2 == 0:
... | 计算二维互相关运算 |
13,658 | import os
import time
import importlib
from ace import util
from ace.logger import Logger
logger = Logger(os.path.basename(__file__))
RESOURCE_LOADER_DIRECTORIES = [
"custom",
"core",
]
def load_resource(resource_class_name, import_path):
try:
module = importlib.import_module(import_path)
except... | null |
13,659 | import os
import sys
import inspect
import psutil
def get_package_root(obj):
package_name = obj.__class__.__module__.split(".")[0]
package_root = os.path.dirname(os.path.abspath(sys.modules[package_name].__file__))
return package_root | null |
13,660 | import os
import sys
import inspect
import psutil
def get_file_directory():
filepath = inspect.stack()[1].filename
return os.path.dirname(os.path.abspath(filepath)) | null |
13,661 | import os
import sys
import inspect
import psutil
def get_system_resource_usage():
# CPU Load
cpu_load = psutil.cpu_percent(interval=1)
cpu_string = f"CPU: {cpu_load}%"
# Memory Details
memory_info = psutil.virtual_memory()
total_memory = memory_info.total / (1024**3) # Convert to GB
free... | null |
13,662 | import os
def get_template_dir():
return os.path.join(os.path.dirname(__file__), "prompts/templates") | null |
13,663 | import os
def get_identities_dir():
return os.path.join(os.path.dirname(__file__), "prompts/identities") | null |
13,664 | import json
import os
from dotenv import load_dotenv
def has_environment_variable(name):
value = os.getenv(name)
return value is not None and value.strip() != "" | null |
13,665 | import json
import os
from dotenv import load_dotenv
def parse_json(input_string):
try:
return json.loads(input_string)
except json.JSONDecodeError:
return None | null |
13,666 | import logging
import os
from ace import constants
logging.basicConfig(level=logging.DEBUG)
def get_log_level(level_str):
level = logging.getLevelName(level_str)
if not isinstance(level, int):
raise ValueError(f"Invalid log level: {level_str}")
return level | null |
13,667 | import layer
import top_layer as top
import openai
import os
from dotenv import load_dotenv
def stream_chat(stream):
chat_message = ""
for item in stream:
chat_message += item
return chat_message | null |
13,668 | import openai
import yaml
from time import time, sleep
from datetime import datetime
import textwrap
import time
from functools import wraps
import glob
import os
from pathlib import Path
def retry(wait_time=360, max_retries=3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
... | null |
13,669 | import openai
import yaml
from time import time, sleep
from datetime import datetime
import textwrap
import time
from functools import wraps
import glob
import os
from pathlib import Path
def get_message_logs(files):
messages = []
for file in files:
with open(file, 'r', encoding='utf-8') as f:
... | null |
13,670 | import openai
import yaml
from time import time, sleep
from datetime import datetime
import textwrap
import time
from functools import wraps
import glob
import os
from pathlib import Path
def chat_print(text):
formatted_lines = [textwrap.fill(line, width=120, initial_indent=' ', subsequent_indent=' ') for li... | null |
13,671 | import ace_layers as ace
def get_messages(layer_num):
try:
# FETCH FROM BUS
north_bus = ace.get_messages('north', layer_num)
north_messages = ace.format_messages(north_bus)
south_bus = ace.get_messages('south', layer_num)
south_messages = ace.format_messages(south_bus)
... | null |
13,672 | import ace_layers as ace
def chat_completion(layer_num, messages):
try:
# FORMAT FOR API
response = ace.get_response(layer_num).strip()
conversation = list()
conversation.append({'role': 'system', 'content': ace.open_file(f"layer{layer_num}.txt").replace('<<INTERNAL>>', response)})
... | null |
13,673 | import ace_layers as ace
def save_response(layer_num, response):
try:
# POST TO BUS
ace.set_response(layer_num, response)
south_out = response.splitlines()[0].replace('SOUTH:','').strip()
north_out = response.splitlines()[1].replace('NORTH:','').strip()
ace.post_message('sou... | null |
13,674 | import ace_layers as ace
def get_messages():
try:
# FETCH FROM BUS
north_bus = ace.get_messages('north', 1)
return ace.format_messages(north_bus)
except Exception as oops:
print(f'\n\nError in GET_MESSAGES of LAYER 1: "{oops}"') | null |
13,675 | import ace_layers as ace
def chat_completion(messages):
try:
# FORMAT FOR API
response = ace.get_response(1).strip()
conversation = list()
conversation.append({'role': 'system', 'content': ace.open_file('layer1.txt').replace('<<INTERNAL>>', response)})
conversation.append({'... | null |
13,676 | import ace_layers as ace
def save_response(response):
try:
ace.set_response(1, response)
ace.post_message('south', 1, response)
return "responses saved"
except Exception as oops:
print(f'\n\nError in SAVE_RESPONSE of LAYER 1: "{oops}"') | null |
13,677 | from flask import Flask, request, Response
import top_layer
import layer
import os
import openai
from flask_cors import CORS, cross_origin
from dotenv import load_dotenv
def get_messages():
layer_num = int(request.args.get('layer'))
if (layer_num > 1):
return layer.get_messages(layer_num), 200
else... | null |
13,678 | from flask import Flask, request, Response
import top_layer
import layer
import os
import openai
from flask_cors import CORS, cross_origin
from dotenv import load_dotenv
def chat_completion():
message = request.json
layer_num = message['layer']
messages = message['messages']
stream = ''
if (layer_... | null |
13,679 | from flask import Flask, request, Response
import top_layer
import layer
import os
import openai
from flask_cors import CORS, cross_origin
from dotenv import load_dotenv
def save_response():
message = request.json
layer_num = message['layer']
response = message['response']
if (layer_num > 1):
r... | null |
13,680 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,681 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,682 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,683 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,684 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,685 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,686 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,687 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,688 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,689 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,690 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,691 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,692 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,693 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,694 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,695 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,696 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,697 | import asyncio
import asyncpg
from typing import Dict, List
import uuid
import json
import aio_pika
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from base.amqp.connection import get_connection
from base.amqp.exchange import create_exchange
from f... | null |
13,698 | from database.models import Base
from database.connection import engine, get_db
from sqlalchemy import text
import logging
logger = logging.getLogger(__name__)
Base = declarative_base()
Base.metadata.create_all(engine)
engine = create_engine(
settings.database_uri,
poolclass=NullPool,
)
def get... | null |
13,699 | from database.connection import get_db
from database.models import RabbitMQLog
from settings import settings
from init import init_db
import logging
import pika
import time
logger = logging.getLogger(__name__)
def callback(ch, method, properties, body):
def get_channel():
settings = Settings(
role_name="Aspiration... | null |
13,700 | from base.prompts import get_action_prompt, get_reasoning_input
from base.settings import Settings
import openai
from database.dao_models import LlmMessage, LayerConfigModel, Prompts, OpenAiGPTChatParameters
from typing import List
import re
import time
from datetime import datetime, timezone
import time
import logging... | null |
13,701 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class TestRun(Base):
__tablename__ = 'test_run'
test_run_id = Column(UUID(as_uuid=True), primary_key=Tr... | null |
13,702 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class AncestralPrompt(Base):
AncestralPrompt.test_runs = relationship("TestRun", order_by=TestRun.test_run_id, b... | null |
13,703 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class AncestralPrompt(Base):
__tablename__ = 'ancestral_prompt'
ancestral_prompt_id = Column(UUID(as_uuid=T... | null |
13,704 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class AncestralPrompt(Base):
__tablename__ = 'ancestral_prompt'
ancestral_prompt_id = Column(UUID(as_uuid=T... | null |
13,705 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class AncestralPrompt(Base):
__tablename__ = 'ancestral_prompt'
ancestral_prompt_id = Column(UUID(as_uuid=T... | null |
13,706 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class RabbitMQLog(Base):
__tablename__ = "rabbitmq_logs"
id = Column(UUID(as_uuid=True), primary_key=True, ... | null |
13,707 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
def create_layer_state(db: Session, layer_name: str, process_messages: bool = False):
db_layer_state = LayerState... | null |
13,708 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class LayerConfig(Base):
def get_all_layer_config(db: Session, layer_name: str):
return (
db.query(Laye... | null |
13,709 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class LayerConfig(Base):
__tablename__ = 'layer_config'
config_id = Column(UUID(as_uuid=True), primary_key=... | null |
13,710 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class LayerState(Base):
__tablename__ = 'layer_state'
layer_id = Column(UUID(as_uuid=True), primary_key=Tru... | null |
13,711 | from .models import LayerConfig, LayerState, RabbitMQLog, AncestralPrompt, TestRun
from sqlalchemy.orm import Session
from sqlalchemy import desc
import uuid
from typing import Optional, List, Dict, Any
class LayerState(Base):
__tablename__ = 'layer_state'
layer_id = Column(UUID(as_uuid=True), primary_key=Tru... | null |
13,713 | import json
import os
from dotenv import load_dotenv
def get_environment_variable(name):
value = os.getenv(name)
if value is None or value.strip() == "":
raise EnvironmentError(f"{name} environment variable not set! Check your .env file.")
return value | null |
13,715 | import asyncio
from dotenv import load_dotenv
from ace.ace_system import AceSystem
from channels.discord.discord_bot import DiscordBot
from channels.web.fastapi_app import FastApiApp
from llm.gpt import GPT
from media.giphy_finder import GiphyFinder
from memory.weaviate_memory_manager import WeaviateMemoryManager
from ... | null |
13,716 | import asyncio
import re
from typing import TypedDict, Callable, Awaitable, Union
class MediaGenerator(TypedDict):
keyword: str
generator_function: Callable[[str], Awaitable[Union[str, None]]]
async def replace_media_prompt_with_media_url_formatted_as_markdown(media_generators: [MediaGenerator], message):
... | null |
13,717 | import asyncio
import re
from typing import TypedDict, Callable, Awaitable, Union
class MediaGenerator(TypedDict):
keyword: str
generator_function: Callable[[str], Awaitable[Union[str, None]]]
async def split_message_by_media(media_generators: [MediaGenerator], message):
segments = []
last_end = 0 # ... | null |
13,718 | from datetime import datetime, timezone
from typing import TypedDict, Dict
class ChatMessage(TypedDict):
sender: str
content: str
time_utc: str # // formatted like 2023-01-30T13:45:00Z
def create_chat_message(sender: str, content: str) -> ChatMessage:
now_utc = datetime.now(timezone.utc)
formatted... | null |
13,719 | from datetime import datetime, timezone
from typing import TypedDict, Dict
class ChatMessage(TypedDict):
sender: str
content: str
time_utc: str # // formatted like 2023-01-30T13:45:00Z
def stringify_chat_message(chat_message: ChatMessage):
return f"<{chat_message['time_utc']}> [{chat_message['sender']}... | null |
13,720 | from datetime import datetime, timezone
from typing import TypedDict, Dict
class Memory(TypedDict):
time_utc: str
content: str
def create_memory(content: str) -> Memory:
return {
"time_utc": datetime.now(timezone.utc).isoformat(),
"content": content
} | null |
13,721 | import httpx
from bs4 import BeautifulSoup
from actions.action import Action
async def get_compressed_web_content(url) -> str:
async with httpx.AsyncClient() as client:
response = await client.get(url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx)
soup = Bea... | null |
13,722 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from flask... | null |
13,723 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.scrollview import ScrollView
from flask... | null |
13,724 | import os
import time
import importlib
from ace import util
from ace.logger import Logger
logger = Logger(os.path.basename(__file__))
def loader(resource_name):
try:
resource_class_name = util.snake_to_class(resource_name)
logger.debug(f"Converted resource_name to resource_class: {resource_class_na... | null |
13,727 | import os
import sys
import inspect
import psutil
def snake_to_class(string):
parts = string.split("_")
return "".join(word.title() for word in parts) | null |
13,728 | import os
import sys
import inspect
import psutil
def get_system_resource_usage():
# CPU Load
cpu_load = psutil.cpu_percent(interval=1)
cpu_string = f"CPU: {cpu_load}%"
# Memory Details
memory_info = psutil.virtual_memory()
total_memory = memory_info.total / (1024 ** 3) # Convert to GB
fr... | null |
13,732 | import logging
import os
from ace import constants
logging.basicConfig(level=logging.DEBUG)
def get_log_level(level_str):
level = logging.getLevelName(level_str)
if not isinstance(level, int):
raise ValueError(f'Invalid log level: {level_str}')
return level | null |
13,733 | from ace.settings import Settings
import aio_pika
from ace.logger import Logger
logger = Logger(__name__)
class Settings(BaseSettings):
name: str
label: str
amqp_host_name: str = (
os.getenv("ACE_RABBITMQ_HOSTNAME") or constants.DEFAULT_RABBITMQ_HOSTNAME
)
amqp_username: str = (
os.... | null |
13,734 | from ace.settings import Settings
import aio_pika
from ace.logger import Logger
logger = Logger(__name__)
class Settings(BaseSettings):
async def teardown_exchange(settings: Settings, channel: aio_pika.Channel, queue_name: str, durable=True):
exchange_name = f"exchange.{queue_name}"
logger.debug(f"Teardown ex... | null |
13,735 | import asyncio
import aio_pika
from ace.settings import Settings
from ace.logger import Logger
logger = Logger(__name__)
class Settings(BaseSettings):
async def get_connection(settings: Settings,
loop=asyncio.get_event_loop(),
max_retries=5,
d... | null |
13,736 | import requests
import json
import re
import openai
from time import time, sleep
from datetime import datetime
from halo import Halo
import textwrap
import yaml
def save_file(filepath, content):
with open(filepath, 'w', encoding='utf-8') as outfile:
outfile.write(content) | null |
13,737 | import requests
import json
import re
import openai
from time import time, sleep
from datetime import datetime
from halo import Halo
import textwrap
import yaml
def open_file(filepath):
with open(filepath, 'r', encoding='utf-8', errors='ignore') as infile:
return infile.read() | null |
13,738 | import requests
import json
import re
import openai
from time import time, sleep
from datetime import datetime
from halo import Halo
import textwrap
import yaml
def send_message(bus, layer, message):
url = 'http://127.0.0.1:900/message'
headers = {'Content-Type': 'application/json'}
data = {'bus': bus, 'la... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.