repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/openms/trafoxml.py | pyteomics/openms/trafoxml.py | """
trafoxml - reader for trafoXML files
========================================
Summary
-------
**trafoXML** is a format specified in the
`OpenMS <http://open-ms.sourceforge.net/about/>`_ project.
It defines a transformation, which is a result of retention time alignment.
This module provides a minimalistic way to... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/openms/__init__.py | pyteomics/openms/__init__.py | from . import featurexml, trafoxml, idxml
| python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/mass/unimod.py | pyteomics/mass/unimod.py | """
unimod - interface to the Unimod database
=========================================
This module provides an interface to the relational Unimod database.
The main class is :py:class:`Unimod`.
Dependencies
------------
This module requires :py:mod:`lxml` and :py:mod:`sqlalchemy`.
"""
# Copyright 2015 Joshua Kle... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/mass/mass.py | pyteomics/mass/mass.py | """
mass - molecular masses and isotope distributions
=================================================
Summary
-------
This module defines general functions for mass and isotope abundance
calculations. For most of the functions, the user can define a given
substance in various formats, but all of them would be reduc... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | true |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/mass/__init__.py | pyteomics/mass/__init__.py | from .mass import *
try:
from . import unimod
except ImportError:
# SQLAlchemy is not available
pass | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/file_helpers.py | pyteomics/auxiliary/file_helpers.py | import sys
import codecs
import re
from functools import wraps
from contextlib import contextmanager
from collections import OrderedDict, defaultdict
import json
import multiprocessing as mp
import threading
import warnings
import os
from abc import ABCMeta
from queue import Empty
from collections.abc import Sequence
... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | true |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/target_decoy.py | pyteomics/auxiliary/target_decoy.py | import re
import operator as op
import math
try:
from collections.abc import Container, Sized
except ImportError:
from collections import Container, Sized
from bisect import bisect_right
from contextlib import contextmanager
try:
import pandas as pd
except ImportError:
pd = None
from .structures impor... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | true |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/patch.py | pyteomics/auxiliary/patch.py | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false | |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/constants.py | pyteomics/auxiliary/constants.py | ### Bulky constants for other modules are defined below.
_nist_mass = {'Ac': {0: (227, 1.0),
206: (206.0145, 0.0),
207: (207.01195, 0.0),
208: (208.01155, 0.0),
209: (209.00949, 0.0),
210: (210.00944, 0.0),
211: (211.00773, 0.0),
212: (212.00781, 0.0),
213: (213.00661, 0.0),
214: (214.006902, 0.0),
... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | true |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/utils.py | pyteomics/auxiliary/utils.py | import base64
import zlib
from functools import wraps
from collections import namedtuple
from urllib.parse import urlparse
import pathlib
try:
import numpy as np
except ImportError:
np = None
try:
import pynumpress
except ImportError:
pynumpress = None
from .structures import PyteomicsError
def pri... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/__init__.py | pyteomics/auxiliary/__init__.py | from .structures import (
PyteomicsError, Charge, ChargeList,
_parse_charge, _parse_ion, BasicComposition,
unitfloat, unitint, unitstr, cvstr,
cvquery)
from .constants import _nist_mass
from .file_helpers import (
_file_obj, _keepstate, _keepstate_method, IteratorContextManager,
FileReader, In... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/psims_util.py | pyteomics/auxiliary/psims_util.py | from functools import partial
try:
from psims.controlled_vocabulary.controlled_vocabulary import (load_psimod, load_xlmod, load_gno, obo_cache, load_unimod, load_psims)
from psims.controlled_vocabulary.relationship import HasValueTypeRelationship
_has_psims = True
except ImportError:
def _needs_psims(n... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/structures.py | pyteomics/auxiliary/structures.py | import re
from collections import defaultdict, Counter
import warnings
_UNIT_CV_INTERN_TABLE = dict()
def clear_unit_cv_table():
"""Clear the module-level unit name and
controlled vocabulary accession table.
"""
_UNIT_CV_INTERN_TABLE.clear()
def _intern_unit_or_cv(unit_or_cv):
"""Intern `unit_o... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/pyteomics/auxiliary/math.py | pyteomics/auxiliary/math.py | from .structures import PyteomicsError
def linear_regression_vertical(x, y=None, a=None, b=None):
"""Calculate coefficients of a linear regression y = a * x + b.
The fit minimizes *vertical* distances between the points and the line.
Requires :py:mod:`numpy`.
Parameters
----------
x, y : arr... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/charge_vs_ph.py | doc/source/charge_vs_ph.py | import pylab
import numpy as np
from pyteomics import electrochem
pHs = np.arange(1, 14, 0.5) # list of values of pH
charges = electrochem.charge('PEPTIDE', pHs) # charge function accepts lists of pHs
pylab.figure()
pylab.plot(pHs, charges)
pylab.title("Charge of peptide 'PEPTIDE' vs pH")
pylab.xlabel('pH')
pylab.yla... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/conf.py | doc/source/conf.py | # -*- coding: utf-8 -*-
#
# Pyteomics tutorial build configuration file, created by
# sphinx-quickstart on Sat Dec 17 23:03:56 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/_static/filtering.py | doc/source/_static/filtering.py | # place this file in the same directory as example files
import pylab
from pyteomics import tandem, pepxml, mzid, auxiliary as aux, pylab_aux as pa
import pandas as pd
import numpy as np
pylab.figure()
with tandem.read('example.t.xml') as tf:
h = pylab.hist([psm['rt'] / 60 for psm in tf], bins=25, label='All IDs')... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/_static/example_fasta.py | doc/source/_static/example_fasta.py | import os
from urllib.request import urlretrieve
import gzip
import matplotlib.pyplot as plt
import numpy as np
from pyteomics import fasta, parser, mass, achrom, electrochem, auxiliary
if not os.path.isfile('yeast.fasta.gz'):
print('Downloading the FASTA file for Saccharomyces cerevisiae...')
urlretrieve(
... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/_static/example_annotation.py | doc/source/_static/example_annotation.py | from pyteomics import pylab_aux as pa, usi
import matplotlib.pyplot as plt
spectrum = usi.proxi(
'mzspec:PXD004732:01650b_BC2-TUM_first_pool_53_01_01-3xHCD-1h-R2:scan:41840',
'massive')
peptide = 'WNQLQAFWGTGK'
pa.annotate_spectrum(spectrum, peptide, precursor_charge=2, backend='spectrum_utils',
ion_types=... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
levitsky/pyteomics | https://github.com/levitsky/pyteomics/blob/17e7f6bad7d273846de0a398a3870afe10c74be6/doc/source/_static/example_msms.py | doc/source/_static/example_msms.py | from pyteomics import mgf, pepxml, mass, pylab_aux
import os
from urllib.request import urlopen, Request
import pylab
# get the files
for fname in ('mgf', 'pep.xml'):
if not os.path.isfile('example.' + fname):
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) ... | python | Apache-2.0 | 17e7f6bad7d273846de0a398a3870afe10c74be6 | 2026-01-05T07:13:10.794267Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/gateways/envoy-ai-gateway/rate-limiting/client.py | blueprints/gateways/envoy-ai-gateway/rate-limiting/client.py | #!/usr/bin/env python3
"""
Test script for token-based rate limiting with GPT and Bedrock Claude
"""
import requests
import json
import time
import subprocess
def get_gateway_url():
"""Auto-detect the Gateway URL using kubectl"""
try:
result = subprocess.run([
'kubectl', 'get', 'gateway', ... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/gateways/envoy-ai-gateway/multi-model-routing/client.py | blueprints/gateways/envoy-ai-gateway/multi-model-routing/client.py | #!/usr/bin/env python3
"""
Multi-Model AI Gateway Test Client
Tests self-hosted models (Qwen3, GPT-OSS) and AWS Bedrock Claude
"""
import requests
import json
import subprocess
import sys
def get_gateway_url():
"""Auto-detect AI Gateway URL"""
try:
result = subprocess.run([
'kubectl', 'get... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/llama-lora-finetuning-trn1/assets/consolidate_adapter_shards_and_merge_model.py | blueprints/training/llama-lora-finetuning-trn1/assets/consolidate_adapter_shards_and_merge_model.py | from optimum.neuron.distributed.checkpointing import (
consolidate_model_parallel_checkpoints_to_unified_checkpoint,
)
from transformers import AutoModel
from argparse import ArgumentParser
from shutil import copyfile
import os
import peft
parser = ArgumentParser()
parser.add_argument(
"-i",
"--input_dir",... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/llama-lora-finetuning-trn1/assets/test_model.py | blueprints/training/llama-lora-finetuning-trn1/assets/test_model.py | from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
import argparse
# Set these as constants
TOKENIZER_PATH = "meta-llama/Meta-Llama-3-8B-Instruct"
BASE_MODEL = "meta-llama/Meta-Llama-3-8B"
SAMPLE_INDICES = [94, 99, 123]
def main():
parser = argparse.ArgumentParser(descr... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/llama-lora-finetuning-trn1/assets/finetune_llama.py | blueprints/training/llama-lora-finetuning-trn1/assets/finetune_llama.py | from dataclasses import dataclass, field
from datasets import load_dataset
from peft import LoraConfig
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
set_seed,
)
from optimum.neuron import NeuronHfArgumentParser as HfArgumentParser
from optimum.neuron import NeuronSFTConfig, NeuronSFTTrain... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/tp_zero1_llama2_7b_hf_pretrain.py | blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/tp_zero1_llama2_7b_hf_pretrain.py | # coding=utf-8
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Modifications Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/modeling_llama_nxd.py | blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/modeling_llama_nxd.py | # coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to G... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/ray_train_llama2.py | blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/ray_train_llama2.py | from argparse import ArgumentParser
import ray
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
from ray.train.torch.xla import TorchXLAConfig
# Use training function from NxD llama2 example
# see: https://awsdocs-neuron.readthedocs-hosted.com/en/latest/libraries/neuronx-distributed/tuto... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/logger.py | blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/logger.py | import os
import sys
import time
import inspect
import requests
import torch
from torch.utils.tensorboard import SummaryWriter
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
import numpy as np
def load_events(event_file):
accumulator = EventAccumulator(event_file)
accumul... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/get_dataset.py | blueprints/training/raytrain-llama2-pretrain-trn1/llama2_pretrain/get_dataset.py | from datasets import load_dataset # Library for loading datasets
from transformers import AutoTokenizer # Library for handling tokenization
from itertools import chain # For efficiently iterating through multiple sequences
import os # For file and directory operations
# Conf... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/nvidia-nim/nim-client/client.py | blueprints/inference/nvidia-nim/nim-client/client.py | import argparse
import asyncio
import time
from os import system
import openai
async def generate(client, prompt, sampling_parameters):
try:
response = await client.chat.completions.create(
model=FLAGS.model_name,
messages=[
{
"role": "system",
... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-rayserve-inf2/openai-client.py | blueprints/inference/vllm-rayserve-inf2/openai-client.py | # pip install openai
# python3 openai-client.py
import os
from openai import OpenAI
# Set up the client
client = OpenAI(
base_url="http://localhost:8000/v1",
api_key="dummy-key" # The key doesn't matter for our custom server, but is required by the SDK
)
def chat_completion_example(messages, model="NousRese... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-nvidia-triton-server-gpu/triton-client/triton-client.py | blueprints/inference/vllm-nvidia-triton-server-gpu/triton-client/triton-client.py | import argparse
import asyncio
import json
import sys
import time # Import the time module
from os import system
import numpy as np
import tritonclient.grpc.aio as grpcclient
from tritonclient.utils import *
def count_tokens(text):
return len(text.split())
def create_request(prompt, stream, request_id, sampli... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/llama3/1/model.py | blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/llama3/1/model.py | # Reference from https://github.com/triton-inference-server/vllm_backend
import asyncio
import json
import os
import threading
from typing import AsyncGenerator
import numpy as np
import triton_python_backend_utils as pb_utils
from vllm import SamplingParams
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/mistral7b/1/model.py | blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/mistral7b/1/model.py | # Reference from https://github.com/triton-inference-server/vllm_backend
import asyncio
import json
import os
import threading
from typing import AsyncGenerator
import numpy as np
import triton_python_backend_utils as pb_utils
from vllm import SamplingParams
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/llama2/1/model.py | blueprints/inference/vllm-nvidia-triton-server-gpu/model_repository/llama2/1/model.py | # Reference from https://github.com/triton-inference-server/vllm_backend
import asyncio
import json
import os
import threading
from typing import AsyncGenerator
import numpy as np
import triton_python_backend_utils as pb_utils
from vllm import SamplingParams
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/stable-diffusion-xl-base-rayserve-inf2/ray_serve_stablediffusion.py | blueprints/inference/stable-diffusion-xl-base-rayserve-inf2/ray_serve_stablediffusion.py | from io import BytesIO
from fastapi import FastAPI
from fastapi.responses import Response
import os
import base64
from ray import serve
app = FastAPI()
neuron_cores = 2
@serve.deployment(name="stable-diffusion-api", num_replicas=1, route_prefix="/")
@serve.ingress(app)
class APIIngress:
def __init__(self, diffu... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/gradio-ui/gradio-app-llama.py | blueprints/inference/gradio-ui/gradio-app-llama.py | import gradio as gr
import requests
import os
# Constants for model endpoint and service name
model_endpoint = "/infer"
# service_name = "http://<REPLACE_ME_WITH_ELB_DNS_NAME>/serve"
service_name = os.environ.get("SERVICE_NAME", "http://localhost:8000")
# Function to generate text
def text_generation(message, histor... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/gradio-ui/gradio-app-stable-diffusion.py | blueprints/inference/gradio-ui/gradio-app-stable-diffusion.py | import gradio as gr
import requests
import os
from PIL import Image
from io import BytesIO
# Constants for model endpoint and service name
model_endpoint = os.environ.get("MODEL_ENDPOINT", "/imagine")
service_name = os.environ.get("SERVICE_NAME", "http://localhost:8000")
# Function to generate image based on prompt
d... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-rayserve-gpu/client.py | blueprints/inference/vllm-rayserve-gpu/client.py | import aiohttp
import asyncio
import os
import time
import logging
import csv
from uuid import uuid4 as random_uuid
import json
# Setup logging configuration
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Constants for model endpoint and service name
model_endpoint = os.getenv("MODEL_E... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-rayserve-gpu/vllm_serve.py | blueprints/inference/vllm-rayserve-gpu/vllm_serve.py | import json
from typing import AsyncGenerator
from fastapi import BackgroundTasks
from starlette.requests import Request
from starlette.responses import StreamingResponse, Response, JSONResponse
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.async_llm_engine import AsyncLLMEngine
from vllm.sampling_... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/stable-diffusion-rayserve-gpu/ray_serve_stablediffusion.py | blueprints/inference/stable-diffusion-rayserve-gpu/ray_serve_stablediffusion.py | from io import BytesIO
from fastapi import FastAPI
from fastapi.responses import Response
import torch
import os
import ray
from ray import serve
app = FastAPI()
@serve.deployment(num_replicas=1)
@serve.ingress(app)
class APIIngress:
def __init__(self, diffusion_model_handle) -> None:
self.handle = dif... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/stable-diffusion-rayserve-gpu/locust/locustfile.py | blueprints/inference/stable-diffusion-rayserve-gpu/locust/locustfile.py | import json
from locust import HttpUser, task, between
class StableDiffusionUser(HttpUser):
wait_time = between(1, 2) # Seconds between requests
@task
def generate_image(self):
prompt = "A beautiful sunset over the ocean"
payload = {
"prompt": prompt
}
headers... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/llama3-8b-instruct-rayserve-inf2/ray_serve_llama3.py | blueprints/inference/llama3-8b-instruct-rayserve-inf2/ray_serve_llama3.py | import os
import time
import torch
from transformers import AutoTokenizer
from transformers_neuronx.llama.model import LlamaForSampling
from transformers import LlamaForCausalLM, LlamaTokenizer, PreTrainedTokenizerFast
from transformers_neuronx import NeuronConfig
from transformers_neuronx import GQA
from transformers_... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/vllm-llama3.1-405b-trn1/docker/neuron_multi_node_runner.py | blueprints/inference/vllm-llama3.1-405b-trn1/docker/neuron_multi_node_runner.py | # NOTE: This API server is used only for demonstrating usage of AsyncEngine
# and simple performance benchmarks. It is not intended for production use.
# For production use, we recommend using our OpenAI compatible server.
# change `vllm/entrypoints/openai/api_server.py` instead.
from vllm.entrypoints.neuron_multi_nod... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/llama2-13b-chat-rayserve-inf2/ray_serve_llama2.py | blueprints/inference/llama2-13b-chat-rayserve-inf2/ray_serve_llama2.py | import os
import logging
from fastapi import FastAPI
from ray import serve
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
from transformers_neuronx.llama.model import LlamaForSampling
from transformers_neuronx.module import save_pretrained_split
app = FastAPI()
llm_model_s... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/blueprints/inference/mistral-7b-rayserve-inf2/ray_serve_mistral.py | blueprints/inference/mistral-7b-rayserve-inf2/ray_serve_mistral.py | # Import necessary libraries and modules
from io import BytesIO
from fastapi import FastAPI
import os
from ray import serve
import torch
# Initialize the FastAPI app
app = FastAPI()
# Define the number of Neuron cores to be used
neuron_cores = 2
# Deployment settings for the API ingress using Ray Serve
@serve.depl... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/infra/trainium-inferentia/examples/dp-bert-large-pretrain/docker/assets/dump_env.py | infra/trainium-inferentia/examples/dp-bert-large-pretrain/docker/assets/dump_env.py | #!/usr/bin/env python3
# Test script to dump the current environment, Neuron devices, EFA devices, etc. for
# troubleshooting
import os
import sys
import subprocess
print("Environment variables:")
for key in os.environ.keys():
print(f"{key} -> {os.environ[key]}")
print("\nCommandline Args:")
for i,a in enumerate(... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/infra/trainium-inferentia/examples/dp-bert-large-pretrain/lib/trn1_dist_ddp.py | infra/trainium-inferentia/examples/dp-bert-large-pretrain/lib/trn1_dist_ddp.py | import torchx.specs as specs
import shlex
import os
import re
# Define the root directory for caching data on shared storage (FSx for Lustre)
CACHE_ROOT = "/data/"
# Create an AppDef based on code snippets borrowed from the TorchX DDP builtin
# see: https://github.com/pytorch/torchx/blob/main/torchx/components/dist... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/infra/jark-stack/src/service/dogbooth.py | infra/jark-stack/src/service/dogbooth.py | from io import BytesIO
from fastapi import FastAPI
from fastapi.responses import Response
import torch
import os
from ray import serve
app = FastAPI()
@serve.deployment(num_replicas=1, route_prefix="/")
@serve.ingress(app)
class APIIngress:
def __init__(self, diffusion_model_handle) -> None:
self.handle... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/infra/jark-stack/src/app/streamlit.py | infra/jark-stack/src/app/streamlit.py | import streamlit as st
import requests
from urllib.parse import urlencode
from PIL import Image
import tempfile
### Update Hostname before building image
base_url=""
st.title("Welcome to dogbooth! :dog:")
st.header("_a place to create images of [v]dog in beautiful scenes._")
prompt = st.chat_input("a photo of a [... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
awslabs/ai-on-eks | https://github.com/awslabs/ai-on-eks/blob/754f4163e145c1344182965d8b41a044aa956f45/infra/emr-spark-rapids/examples/xgboost/etl-xgboost-train-transform.py | infra/emr-spark-rapids/examples/xgboost/etl-xgboost-train-transform.py | import time
import os
import sys
from pyspark import broadcast, SparkContext
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession, HiveContext
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.window import Window
# Import ML Libraries
from xgboost.spark import Spar... | python | Apache-2.0 | 754f4163e145c1344182965d8b41a044aa956f45 | 2026-01-05T07:12:30.786413Z | false |
mengdeer589/PythonSizeCruncher | https://github.com/mengdeer589/PythonSizeCruncher/blob/7ccd528adbdb5b74eb88eff1aa10fd05c42a28b5/main.py | main.py | # -*- coding: utf-8 -*-
"""本脚本用于打包后的程序瘦身"""
import json
import os
import sys
import threading
from _tkinter import TclError
from pathlib import Path
from tkinter import *
from tkinter import filedialog, messagebox
from tkinter.ttk import *
from typing import List
# 记录白名单文件路径
WHITE_FILE = Path(__file__).parent.joinpat... | python | MIT | 7ccd528adbdb5b74eb88eff1aa10fd05c42a28b5 | 2026-01-05T07:13:15.175986Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/convert_sillytavern_cards_to_data.py | convert_sillytavern_cards_to_data.py | from PIL import Image
from bw_utils import get_child_paths,lang_detect,is_image,decode_base64,save_json_file,create_dir
import PIL.PngImagePlugin
import os
import json
card_dir = "./data/sillytavern_cards"
names = os.listdir(card_dir)
for name in names:
path = os.path.join(card_dir, name)
role_code = name.spl... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/bw_utils.py | bw_utils.py | import os
import pickle
import json
import logging
import datetime
import re
import random
import base64
MODEL_NAME_DICT = {
"gpt-3.5":"openai/gpt-3.5-turbo",
"gpt-4":"openai/gpt-4",
"gpt-4o":"openai/gpt-4o",
"gpt-4o-mini":"openai/gpt-4o-mini",
"gpt-3.5-turbo":"openai/gpt-3.5-turbo",
"deepseek-... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/BookWorld.py | BookWorld.py | from datetime import datetime
from tqdm import tqdm
import json
import os
import warnings
import random
from typing import Any, Dict, List, Optional, Literal
from collections import defaultdict
import uuid
from bw_utils import *
from modules.main_role_agent import RPAgent
from modules.world_agent import WorldAgent
f... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | true |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/server.py | server.py | from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse
import uvicorn
import json
import asyncio
import os
from pathlib import Path
from datetime import datetime
from bw_utils import is_imag... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/extract_data/extract_data.py | extract_data/extract_data.py | import sys
sys.path.append("../")
from bw_utils import *
from extract_utils import *
import os
import csv
import json
config = load_json_file("./extract_config.json")
def get_default_character_info(role_name,language,other_role_names):
default_character_info = {
"role_name": role_name,
"role_code": conv... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/extract_data/extract_settings.py | extract_data/extract_settings.py | import sys
sys.path.append("../")
from bw_utils import *
from extract_utils import *
import os
config = load_json_file("./extract_config.json")
book_path = config["book_path"]
book_name = os.path.basename(book_path).split(".")[0]
language = config["language"] if config["language"] else lang_detect(book_name)
book_sou... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/extract_data/extract_utils.py | extract_data/extract_utils.py | import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
import os
import json
import chardet
from bw_utils import *
import re
import pdfplumber
def extract_text_by_bookmark(book, start_href, end_href = ""):
"""
end_href: 搜索截止处。若为空字符串则直接搜索到结尾
"""
# 查找 href 对应的章节
start_name = start_hr... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/memory.py | modules/memory.py | import sys
sys.path.append("../")
from bw_utils import *
from modules.embedding import get_embedding_model
try:
from langchain_experimental.generative_agents.memory import GenerativeAgentMemory
except Exception:
from langchain_experimental.generative_agents import GenerativeAgentMemory
try:
from langchai... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/history_manager.py | modules/history_manager.py | from typing import Any, Dict, List, Optional, Literal
from collections import defaultdict
from datetime import datetime
from bw_utils import load_json_file, save_json_file, load_jsonl_file, save_jsonl_file
import os
class HistoryManager:
def __init__(self):
self.detailed_history = []
def add_record(s... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/world_agent.py | modules/world_agent.py | import sys
sys.path.append("../")
import csv
from typing import Any, Dict, List, Optional, Literal
from bw_utils import *
from modules.embedding import get_embedding_model
class WorldAgent:
# Init
def __init__(self,
world_file_path: str,
location_file_path: str,
... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/embedding.py | modules/embedding.py | import sys
sys.path.append("../")
from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space
from modelscope import AutoModel, AutoTokenizer
from functools import partial
from bw_utils import get_child_folders
import torch
import os
class EmbeddingModel(EmbeddingFunction[Documents]):
def __ini... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/main_role_agent.py | modules/main_role_agent.py | import sys
from collections import defaultdict
sys.path.append("../")
import os
from typing import Any, Dict, List, Optional, Literal
from modules.embedding import get_embedding_model
from modules.memory import build_role_agent_memory
from modules.history_manager import HistoryManager
from bw_utils import *
import rand... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/eval_agent.py | modules/eval_agent.py | import sys
from flask import Response
sys.path.append("../")
from typing import Any, Dict, List, Optional, Literal
from collections import defaultdict
from bw_utils import *
from modules.prompt.eval_prompt import DEDUCT_PROMPT_DICT,PLUS_PROMPT_DICT, TTCW_PROMPT_DICT, SCRIPT_GENERATION_PROMPT,SCORING_PROMPT_DICT,SCRIPT... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/db/BaseDB.py | modules/db/BaseDB.py | # BaseDB.py
from abc import ABC, abstractmethod
class BaseDB(ABC):
@abstractmethod
def init_from_data(self, data):
pass
@abstractmethod
def search(self, query, n_results):
pass
| python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/db/ChromaDB.py | modules/db/ChromaDB.py | import chromadb
from .BaseDB import BaseDB
import os
from tqdm import tqdm
import uuid
class ChromaDB(BaseDB):
def __init__(self, embedding, save_type="persistent"):
try:
self.collections = {}
self.embedding = embedding
base_dir = os.path.dirname(os.path.abspath(__file_... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/DeepSeek.py | modules/llm/DeepSeek.py | from .BaseLLM import BaseLLM
from openai import OpenAI
import os
class DeepSeek(BaseLLM):
def __init__(self, model="deepseek-chat"):
super(DeepSeek, self).__init__()
self.client = OpenAI(
api_key=os.getenv("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
)
... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/LangChainGPT.py | modules/llm/LangChainGPT.py | from .BaseLLM import BaseLLM
from openai import OpenAI
import os
class LangChainGPT(BaseLLM):
def __init__(self, model="gpt-4o-mini"):
super(LangChainGPT, self).__init__()
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.model_name = model
# add api_base
... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/BaseLLM.py | modules/llm/BaseLLM.py | from abc import ABC, abstractmethod
class BaseLLM(ABC):
def __init__(self):
pass
@abstractmethod
def initialize_message(self):
pass
@abstractmethod
def ai_message(self, payload):
pass
@abstractmethod
def system_message(self, payload):
pass
@a... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/Ollama.py | modules/llm/Ollama.py | from .BaseLLM import BaseLLM
import requests
import json
class OllamaLLM(BaseLLM):
def __init__(self, model="llama2"):
super(OllamaLLM, self).__init__()
self.model_name = model
self.base_url = "http://localhost:11434/api"
self.messages = []
def initialize_message(self):
... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/VLLM.py | modules/llm/VLLM.py | from .BaseLLM import BaseLLM
from vllm import LLM, SamplingParams
class LocalVLLM(BaseLLM):
def init(
self,
model,
tensor_parallel_size=1,
trust_remote_code=False,
dtype="auto",
max_model_len=None,
gpu_memory_utilization=0.90,
seed=None,
enforce_eager=False,
**llm_kwargs
... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/Claude.py | modules/llm/Claude.py | import anthropic
import json
import requests
import os
import __main__
from typing import Dict, List
from .BaseLLM import BaseLLM
class Claude(BaseLLM):
def __init__(self, model="claude-3-5-sonnet-latest"):
super(Claude, self).__init__()
self.model_name = model
self.client = anthropic.Ant... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/Doubao.py | modules/llm/Doubao.py | from .BaseLLM import BaseLLM
from volcenginesdkarkruntime import Ark
import os
class Doubao(BaseLLM):
def __init__(self, model="ep-20241228220355-cqxcs"):
super(Doubao, self).__init__()
self.client = Ark(api_key=os.environ.get("ARK_API_KEY"))
self.model_name = model
self.messag... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/Qwen.py | modules/llm/Qwen.py | from .BaseLLM import BaseLLM
from openai import OpenAI
import os
class Qwen(BaseLLM):
def __init__(self, model="qwen-max"):
# qwen-max, qwen-plus, qwen-turbo
super(Qwen, self).__init__()
self.client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashsc... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/Gemini.py | modules/llm/Gemini.py | from .BaseLLM import BaseLLM
from google import genai
import os
import time
class Gemini(BaseLLM):
def __init__(self, model="gemini-2.0-flash"):
super(Gemini, self).__init__()
self.model_name = model
self.messages = []
def initialize_message(self):
self.messages = []
def ... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/OpenRouter.py | modules/llm/OpenRouter.py | from .BaseLLM import BaseLLM
import os
from openai import OpenAI
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4o")
class OpenRouter(BaseLLM):
def __init__(self, model="deepseek/deepseek-r1:free"):
super(OpenRouter, self).__init__()
self.client = OpenAI(
api_key=os.getenv("OPE... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/llm/LocalModel.py | modules/llm/LocalModel.py | from .BaseLLM import BaseLLM
from peft import PeftModel
import os
from transformers import AutoModelForCausalLM, AutoTokenizer
class LocalModel(BaseLLM):
def __init__(self, model, adapter_path = None):
super(LocalModel, self).__init__()
model_name = model
self.model = AutoModelForCausalLM.... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/prompt/world_agent_prompt_zh.py | modules/prompt/world_agent_prompt_zh.py | SCRIPT_ATTENTION_PROMPT = """
注意这个故事的剧本如下:
{script}
"""
SELECT_SCREEN_ACTORS_PROMPT = """
你是一个熟练的剧本作家,从备选角色列表中选择下一幕的出场角色们,增强戏剧性。为了完成幕的切换,禁止选择最近刚行动过的角色{previous_role_codes}。
## 角色信息及位置,括号内为role_code
{roles_info}
## 历史记录
{history_text}
## 当前事件
{event}
## 要求:
1.选中的角色当前必须身处同一地点。
返回选中角色的role_code列表,它应该能被eval()解析。不要包含任何... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/prompt/role_agent_prompt_en.py | modules/prompt/role_agent_prompt_en.py | INTERVENTION_PROMPT = """
!!!Current Global Event:{intervention}
"""
SCRIPT_ATTENTION_PROMPT = """
!!!Notice that your action should be consistent with the script.
The Script:{script}
"""
ROLE_MOVE_PROMPT = """
You are {role_name}. You shoule decide whether to move based on your goal. Move only when it is necessary... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/prompt/eval_prompt.py | modules/prompt/eval_prompt.py | SCORING_PROMPT_DICT = {
"comparison_template": """You are a literary critic specializing in character analysis and dialogue evaluation.
Given two simulated conversations for a plot in {source}, your task is to compare these two conversations based on the following steps:
1. Read and understand the provided materi... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | true |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/prompt/role_agent_prompt_zh.py | modules/prompt/role_agent_prompt_zh.py | INTERVENTION_PROMPT = """
!!!当前的全局事件:{intervention}
"""
SCRIPT_ATTENTION_PROMPT = """
!!!注意角色应当服从剧本
剧本:{script}
"""
ROLE_MOVE_PROMPT = """
你是 {role_name}。你需要结合你的目标决定是否移动到另一地点。**仅当必要或与你的目标强相关时,才选择移动。**
{profile}
你的目标:{goal}
你的当前状态:{status}
## 历史对话记录
{history}
## 你所在的地点
{location}
## 你可以前往的地点及处在该地点的角色
{locations... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
alienet1109/BookWorld | https://github.com/alienet1109/BookWorld/blob/a00371637ca805bf4625d4610c74764f9d83bdc2/modules/prompt/world_agent_prompt_en.py | modules/prompt/world_agent_prompt_en.py | SCRIPT_ATTENTION_PROMPT = """
!!!Notice that the script of the story is:
{script}
"""
SELECT_SCREEN_ACTORS_PROMPT = """
You are a skilled screenwriter tasked with selecting the characters for the next scene from the list of available roles to enhance the drama.
To ensure the transition between scenes, you should not ... | python | Apache-2.0 | a00371637ca805bf4625d4610c74764f9d83bdc2 | 2026-01-05T07:13:13.984934Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/scripts/preprocess_dataset.py | scripts/preprocess_dataset.py | import time
from argparse import ArgumentParser
from importlib.metadata import version
from pathlib import Path
from llm_jp_eval.jaster import DatasetRegistry
all_processors = DatasetRegistry.list_registered()
def main():
parser = ArgumentParser()
parser.add_argument("-d", "--dataset-name", type=str, requi... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/scripts/evaluate_llm.py | scripts/evaluate_llm.py | import logging
from llm_jp_eval.cli import setup_cli
from llm_jp_eval.evaluator import evaluate, load_dataset_and_construct_prompt_template
from llm_jp_eval.schemas import EvaluationConfig
logger = logging.getLogger(__name__)
def evaluation(cfg: EvaluationConfig) -> None:
_ = evaluate(cfg)
def dump_prompts(cf... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/schemas.py | src/llm_jp_eval/schemas.py | import base64
import hashlib
import importlib
import importlib.metadata
import json
from functools import cached_property
from pathlib import Path
from typing import Any, Literal
import yaml
from pydantic import (
BaseModel,
ConfigDict,
DirectoryPath,
Field,
FilePath,
SerializeAsAny,
comp... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/prompts.py | src/llm_jp_eval/prompts.py | # jinja template for evaluation prompt (Japanese)
evaluation_prompt_template = """
{%- if dataset_instruction -%}
### 指示
{{ dataset_instruction }}
{% endif -%}
{%- if answer_pattern %}
### 回答形式
{{ answer_pattern }}
{% endif -%}
{%- if few_shots %}
<examples>
{%- for shot in few_shots %}
<example_{{ loop.index }}>
### 入... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/cli.py | src/llm_jp_eval/cli.py | import argparse
import logging
import sys
from typing import Callable, Type, TypeVar
from pydantic import BaseModel, FilePath
from pydantic_settings import BaseSettings, CliApp, PydanticBaseSettingsSource, YamlConfigSettingsSource
logger = logging.getLogger(__name__)
# https://github.com/pydantic/pydantic-settings... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/online_inference.py | src/llm_jp_eval/online_inference.py | import os
from typing import Annotated, Literal
import openai
from langchain_community.llms import VLLMOpenAI
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, ConfigDict, Field
# https://platform.openai.com/docs/api-reference/chat/create
class OpenAIGenerationConfig(BaseModel):
model_con... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/evaluator.py | src/llm_jp_eval/evaluator.py | import json
import logging
from datetime import datetime
from pathlib import Path
from statistics import mean
from typing import Any, Dict, Optional, Tuple
import numpy as np
import torch
from fuzzywuzzy import fuzz
from tqdm import tqdm
from llm_jp_eval.answer_parser import AnswerPatternId, extract_answer_with_pat... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/utils.py | src/llm_jp_eval/utils.py | import asyncio
import json
import logging
import random
import re
import sys
import unicodedata
import warnings
from contextlib import contextmanager
from enum import Enum
from pathlib import Path, PosixPath
from typing import TYPE_CHECKING, Any, Literal, TypedDict
import jinja2
import numpy as np
import torch
import... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/logging.py | src/llm_jp_eval/logging.py | import logging
import sys
def setup_logging(
level=logging.INFO,
format_str="[%(asctime)s] %(levelname)s - %(name)s: %(message)s",
date_format="%Y-%m-%d %H:%M:%S",
handler=None,
) -> None:
root_logger = logging.getLogger()
root_logger.setLevel(level)
if handler is None:
handler = ... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/__init__.py | src/llm_jp_eval/__init__.py | __version__ = "2.0.0"
| python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/answer_parser.py | src/llm_jp_eval/answer_parser.py | import re
from enum import Enum
from typing import Dict
class AnswerPatternId(str, Enum):
CUSTOM = "custom"
DATASET = "dataset"
ANSWER_TAGS_JP = "answer_tags_jp"
ANSWER_TAGS_EN = "answer_tags_en"
CHOICE_ONLY_JP = "choice_only_jp"
CHOICE_ONLY_EN = "choice_only_en"
JSON_OUTPUT_JP = "json_ou... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/metrics/metrics.py | src/llm_jp_eval/metrics/metrics.py | import ast
import functools
import json
import logging
import math
import re
import string
import subprocess
import sys
import textwrap
from abc import ABC, abstractmethod
from collections import defaultdict
from pathlib import Path
from statistics import mean
from typing import Callable, ClassVar, Type
import bert_s... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/metrics/rouge_ja.py | src/llm_jp_eval/metrics/rouge_ja.py | """Rouge Score for Japanese
ROUGE の演算は Google の rougescore を使用する。
(Rogue Scores という論文によると、Google の rougescore は Rouge の再実装として一部を除き正確に再現しているとのこと)
https://aclanthology.org/2023.acl-long.107/
Tokenizer には sacrebleu で使用されている日本語 Tokenizer を使用する。
This script uses Google's rougescore for ROUGE calculation.
(According to th... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/metrics/__init__.py | src/llm_jp_eval/metrics/__init__.py | from .rouge_ja import RougeJa
__all__ = ["RougeJa"]
| python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/metrics/sandbox_client.py | src/llm_jp_eval/metrics/sandbox_client.py | # simplified version of the code from
# https://github.com/langgenius/dify/blob/main/api/core/helper/code_executor/code_executor.py
import logging
from enum import Enum
from threading import Lock
from typing import Optional
from httpx import Timeout, get, post
from pydantic import BaseModel
from pydantic_settings im... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
llm-jp/llm-jp-eval | https://github.com/llm-jp/llm-jp-eval/blob/a5b71613317dfc051714585740f5a2be006ea1d0/src/llm_jp_eval/metrics/mifeval/instructions_registry.py | src/llm_jp_eval/metrics/mifeval/instructions_registry.py | # https://github.com/lightblue-tech/M-IFEval/blob/0bc3143a919eef2f9ec64aa26da8a546086653de/instructions_registry.py
# type: ignore
# coding=utf-8
# Copyright 2024 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... | python | Apache-2.0 | a5b71613317dfc051714585740f5a2be006ea1d0 | 2026-01-05T07:13:14.125338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.