date_collected
stringclasses
1 value
repo_name
stringlengths
6
116
file_name
stringlengths
2
220
file_contents
stringlengths
13
357k
prompts
list
2024-01-10
SBrandeis/transformers
src~transformers~models~openai~modeling_tf_openai.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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...
[]
2024-01-10
Lucete28/TradeTrend
TT_runfile~update_naver_raw.py
from airflow.models.variable import Variable import openai import pandas as pd openai.api_key = Variable.get("gpt_api_key") Target_list = Variable.get("Target_list") values = [tuple(item.strip("()").split(",")) for item in Target_list.split("),")] values = [(x[0].strip(), x[1].strip()) for x in values] err_report =...
[ "PLACEHOLDER PLACEHOLDER ๊ด€๋ จ ๋‰ด์Šค๊ธฐ์‚ฌ ์ œ๋ชฉ์ธ๋ฐ PLACEHOLDER ์ฃผ์‹์— ๋ฏธ์น  ๊ธ์ •๋„์˜ ํ‰๊ท ์„ 0์—์„œ 1์‚ฌ์ด ์†Œ์ˆซ์  ๋‘์ž๋ฆฌ๊นŒ์ง€ ๋‚˜ํƒ€๋‚ด float๊ฐ’๋งŒ" ]
2024-01-10
LilithHafner/ai
integrated_ai.py
import openai openai.api_key = "sk-..." # GPT AI def ai(prompt): response = openai.Completion.create( engine="code-davinci-002", prompt=prompt, temperature=0, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0, stop="<end>" ) return response.cho...
[ "This is a question and answer bot that has oracles to various external tools including python, google, and others\n\n<user input>what time is it<end>\n<pyhton eval>time.ctime()<end>\n<python eval result>Traceback (most recent call last):\n File \"/Users/x/Documents/integrated_ai.py\", line 26, in python\n retu...
2024-01-10
Kororinpas/Lit_Tool
document_util.py
def get_split_documents(docs, chunk_size, chunk_overlap): from langchain.text_splitter import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,chunk_overlap=chunk_overlap) return text_splitter.split_documents(docs)
[]
2024-01-10
Kororinpas/Lit_Tool
literature_test.py
import streamlit as st import sys class StreamlitWriter: def write(self, text): st.write(text.strip()) ### This the function about streamlit def Vector_Databse(): st.write("Vector Database") choose = st.radio("Choose using an existing database or upload a new one.", ["Using ...
[ "\n Given the document and query, find PLACEHOLDER sentences in the document that are most similar in meaning to the query. \n Return the sentences, the meta source of the sentences and the cosine similarity scores. \n If no similar sentences is found, return the sentence with highest cosine siliarity scor...
2024-01-10
Kororinpas/Lit_Tool
pdf_retrieval.py
from operator import itemgetter from langchain.chat_models import ChatOpenAI from langchain.output_parsers import StructuredOutputParser, ResponseSchema from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate from langchain.document_loaders import DataFrameLoader, PyMuPDFLoader import os import f...
[ "sample_introes", "words_limit", "format_instructions", "\n I have extracted text from the initial pages of a Journal of Economic Literature (JEL) PDF file. I require assistance in extracting \n specific details, namely: article title, author, abstract and keywords section. Pleas...
2024-01-10
Kororinpas/Lit_Tool
pdf_documents.py
from pdf_metadata import get_pdf_metadata from pdf_metadata_llm import get_pdf_metadata_using_llm def get_pdf_documents(pdf_files): from langchain.document_loaders import PyMuPDFLoader,DirectoryLoader,UnstructuredPDFLoader docs =[] import re for pdf_fullpath in pdf_files: metadata = get_pdf_metadata(pdf...
[]
2024-01-10
Kororinpas/Lit_Tool
pdf_metadata_llm.py
from doi import get_doi from document_util import get_split_documents def get_pdf_metadata_using_llm(doc): import re doc[0].page_content = re.sub('\n+',' ',doc[0].page_content.strip()) # from langchain.text_splitter import RecursiveCharacterTextSplitter # text_splitter = RecursiveCharacterTextSplitter(...
[]
2024-01-10
Kororinpas/Lit_Tool
cosine_match.py
def search_cosine_similarity(query,split_docs,embeddings): ##query-str,split_docs-list,embeddings-embeddings() split_docs_content = [content['content'] for content in split_docs] embed_docs = embeddings.embed_documents(split_docs_content) embed_query= embeddings.embed_query(query) from openai.embe...
[]
2024-01-10
Kororinpas/Lit_Tool
embedding_function.py
def get_embedding_function(): from langchain.embeddings import HuggingFaceEmbeddings import torch device = 'cuda' if torch.cuda.is_available() else 'cpu' model_name = "sentence-transformers/all-mpnet-base-v2" model_kwargs = {'device':device} return HuggingFaceEmbeddings(model_name=model_name...
[]
2024-01-10
Kororinpas/Lit_Tool
doi.py
def get_doi(abstract): from kor.extraction import create_extraction_chain from kor.nodes import Object, Text, Number from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) # type: ignore schema = Object( id="doi", description="doi is a digital ide...
[]
2024-01-10
jied-O/Jids-Garage
langchainagentstest.py
from langchain import OpenAI from langchain.chains import LLMChain from langchain.chains import PALChain from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.agents import load_tools from ogbujipt.config import openai_emulation from ogbujipt.model_style.alpaca import prep...
[ "What is the capital of {place}?" ]
2024-01-10
tarunsamanta2k20/quivr
backend~parsers~audio.py
import os import tempfile import time from io import BytesIO from tempfile import NamedTemporaryFile import openai from fastapi import UploadFile from langchain.document_loaders import TextLoader from langchain.embeddings.openai import OpenAIEmbeddings from langchain.schema import Document from langchain.text_splitter...
[]
2024-01-10
sshh12/llm_optimize
llm_optimize~optimize.py
from typing import Callable, Optional, Tuple, List import re import openai from langchain.input import print_text from langchain.prompts.chat import ( SystemMessage, HumanMessage, AIMessage, ) from llm_optimize import llm, constants # The numeric score and the LLM-facing representation ScoreTuple = Tuple...
[]
2024-01-10
xiahan4956/Auto_Claude_100k
autogpt~llm~api_manager.py
from __future__ import annotations from typing import List, Optional import openai from openai import Model from autogpt.config import Config from autogpt.llm.base import CompletionModelInfo, MessageDict from autogpt.llm.providers.openai import OPEN_AI_MODELS from autogpt.logs import logger from autogpt.singleton im...
[]
2024-01-10
xiahan4956/Auto_Claude_100k
autogpt~llm~utils~claude.py
from autogpt.config import Config import time import openai import json CFG = Config() openai.api_key = CFG.openai_api_key MAX_TOKEN_ONCE = 100000 CONTINUE_PROMPT = "... continue" from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT def _sendReq(anthropic, prompt, max_tokens_to_sample): print("----------...
[ "f\"{question} {anthropic.AI_PROMPT}", "1. You will receive a JSON string, and your task is to extract information from it and return it as a JSON object. 2.Use function's json schema to extrct.Please notice the format 3. Be aware that the given JSON may contain errors, so you may need to infer the fields and t...
2024-01-10
pkrack/asp
asp~ppo_patched.py
import warnings from typing import Any, Dict, Optional, Type, TypeVar, Union import numpy as np import torch as th from gymnasium import spaces from stable_baselines3.common.on_policy_algorithm import OnPolicyAlgorithm from stable_baselines3.common.policies import ActorCriticCnnPolicy, ActorCriticPolicy, BasePolicy, M...
[]
2024-01-10
jongio/chat-with-your-data-solution-accelerator
backend~utilities~orchestrator~Strategies.py
from enum import Enum class OrchestrationStrategy(Enum): OPENAI_FUNCTION = 'openai_function' LANGCHAIN = 'langchain' def get_orchestrator(orchestration_strategy: str): if orchestration_strategy == OrchestrationStrategy.OPENAI_FUNCTION.value: from .OpenAIFunctions import OpenAIFunctionsOrchestrator...
[]
2024-01-10
jongio/chat-with-your-data-solution-accelerator
backend~utilities~document_chunking~Layout.py
from typing import List from .DocumentChunkingBase import DocumentChunkingBase from langchain.text_splitter import MarkdownTextSplitter from .Strategies import ChunkingSettings from ..common.SourceDocument import SourceDocument class LayoutDocumentChunking(DocumentChunkingBase): def __init__(self) -> None: ...
[]
2024-01-10
jongio/chat-with-your-data-solution-accelerator
backend~utilities~helpers~LLMHelper.py
import openai from typing import List from langchain.chat_models import AzureChatOpenAI from langchain.embeddings import OpenAIEmbeddings from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from .EnvHelper import EnvHelper class LLMHelper: def __init__(self): env_helper: EnvHelp...
[]
2024-01-10
pcc2k00/HousingPriceTrend
HousingPriceTrendMetaphor.py
import openai import yaml from metaphor_python import Metaphor with open("pass.yml") as f: content = f.read() my_credentials = yaml.load(content, Loader=yaml.FullLoader) openai.api_key = my_credentials["openAi"] metaphor = Metaphor(my_credentials["metaphor"]) USER_QUESTION = "Recent housing price in Seattle" ...
[]
2024-01-10
romain-cambonie/openxcom-mod-generator
src~chat~ask_for_visual_proposition.py
from openai import OpenAI from openai.types.chat import ChatCompletion def ask_for_concept_art( client: OpenAI, character_story: str, art_style_description: str, ) -> str: system_prompt = ( "Generate a comprehensive and vivid visual concept art of a character for a piece of artwork. " ...
[ "Generate a comprehensive and vivid visual concept art of a character for a piece of artwork. The character should fit within a distinct theme and style, and the description must be detailed enough to guide an artist in creating a dynamic and engaging image.Here are the guidelines for your description:Theme and Set...
2024-01-10
romain-cambonie/openxcom-mod-generator
src~dalle~call_dalle_and_save_image.py
import requests from openai import OpenAI from pathlib import Path from typing import Optional from openai.types import ImagesResponse def call_dalle_and_save_image(prompt: str, client: OpenAI, output_file_path: Path) -> Optional[Path]: try: # Generate image using OpenAI client response: ImagesRe...
[]
2024-01-10
romain-cambonie/openxcom-mod-generator
src~chat~ask_for_dalle_character_prompt.py
from openai import OpenAI from openai.types.chat import ChatCompletion def ask_for_dalle_character_prompt( client: OpenAI, concept_art_description: str, ) -> str: system_prompt = ( "You're given a detailed concept art description of a character. Your task is to condense this description into a " ...
[ "Transform the above concept art description into a succinct DALL-E prompt.", "You're given a detailed concept art description of a character. Your task is to condense this description into a succinct, vivid DALL-E prompt.The DALL-E prompt should accurately capture the key visual elements and artistic style descr...
2024-01-10
romain-cambonie/openxcom-mod-generator
src~chat~ask_for_origin_story.py
from openai import OpenAI from openai.types.chat import ChatCompletion def ask_for_origin_story( client: OpenAI, character_name: str, equipment_description: str, appearance_description: str, ) -> str: system_prompt = ( "You are tasked with creating a short origin story for a fictional char...
[ "You are tasked with creating a short origin story for a fictional character. You will receive three key pieces of information: (1) the character's name, (2) a YAML payload detailing the character's equipment, and (3) an image that shows some characteristics of the character's appearance. Your job is to weave these...
2024-01-10
outlines-dev/outlines
outlines~models~__init__.py
"""Module that contains all the models integrated in outlines. We group the models in submodules by provider instead of theme (completion, chat completion, diffusers, etc.) and use routing functions everywhere else in the codebase. """ from .awq import awq from .exllamav2 import exl2 from .gptq import gptq from .llam...
[]
2024-01-10
ball2004244/Pinecone-Hackathon-23-Backend
logic~pinecone_db.py
''' This file contains the logic for storing and querying data from Pinecone. ''' from typing import List from langchain.vectorstores import Pinecone from langchain.chains.summarize import load_summarize_chain from langchain.llms import GooglePalm from langchain.embeddings.google_palm import GooglePalmEmbeddings from l...
[]
2024-01-10
TheoKanning/crossword
crossword~clues.py
import json import os import openai def convert_raw_clues(raw_filename, output_filename): """ Reads raw clue info from raw_filename, formats it to match GPT-3's fine-tune input, and writes it to output_filename Raw clues are formatted like "Up in the air : ALOFT" """ with open(output_filename, ...
[ "f\"Answer: {answer.lower()}\\nClue:" ]
2024-01-10
NusretOzates/langchain_retrieval_qa_bot
data_loaders.py
import re from itertools import chain from typing import List from langchain.docstore.document import Document from langchain.document_loaders import PyPDFLoader, TextLoader, UnstructuredURLLoader from langchain.indexes import VectorstoreIndexCreator from langchain.text_splitter import RecursiveCharacterTextSplitter f...
[]
2024-01-10
Antrozhuk/telegramChatGPTBot
src~telegram_bot.py
import telegram.constants as constants from telegram import Update from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters from src.openai_helper import OpenAIHelper from src.logger import Logger class ChatGPT3TelegramBot: """ Class representing a Chat-GPT3 Telegram...
[]
2024-01-10
aws-samples/aurora-postgresql-pgvector
DAT303~02_QuestionAndAnswering~rag_app.py
# Import libraries from dotenv import load_dotenv from PyPDF2 import PdfReader from langchain.vectorstores.pgvector import PGVector from langchain.memory import ConversationSummaryBufferMemory from langchain.chains import ConversationalRetrievalChain from htmlTemplates import css from langchain.text_splitter import Rec...
[]
2024-01-10
WuQingYi20/InteractiveStory
wsgi.py
from flask import Flask, render_template, jsonify, request import openai import re from prompts import prompts from dotenv import load_dotenv import os # Load the .env file load_dotenv() app = Flask(__name__) initialCall = True currentDescription = "" # Initialize OpenAI API with your API key openai.api_key = os.g...
[ "\n", "PLACEHOLDER PLACEHOLDER", "PLACEHOLDER", "originalStory + \"\\n\" + prompts['next-page']['story']", "next-page", "originalStory + \"\\n\" + prompts['next-page']['summary']", "originalStory + response_story.choices[0].message['content'] + \"\\n\" + prompts['next-page']['choices']", "content", ...
2024-01-10
yamdereneko/ymbot
src~chatGPT~Chat_GPT_API.py
# -*- coding: utf-8 -*- import asyncio import nonebot from pydantic import BaseModel from httpx import AsyncClient import src.Data.jx3_Redis as redis import openai class Response(BaseModel): """่ฟ”ๅ›žๆ•ฐๆฎๆจกๅž‹""" id: str """็Šถๆ€็ """ object: str created: int model: str choices: list """่ฟ”ๅ›žๆถˆๆฏๅญ—็ฌฆไธฒ""...
[]
2024-01-10
kaistAI/SelFee
data_augmentation~call_openai_multiprocessing_sharegpt.py
from concurrent.futures import ProcessPoolExecutor import argparse import multiprocessing import openai from time import sleep from random import random import nltk nltk.download('punkt') from nltk import tokenize import json import fcntl from typing import List import os from tenacity import ( retry, sto...
[ "Revise the answer based on your own critique within 500 words. Your revision should be simple and clear, so do not add any rhetorics such as apology for the past mistake. Write as if the revised answer is the first try.\nRevision:", "PLACEHOLDER", "Revise the answer based on your own critique within 500 words....
2024-01-10
kaistAI/SelFee
evaluation~gpt4_automatic_evaluation.py
"""This code is sourced from 4960ca7 commit of https://github.com/lm-sys/FastChat/blob/main/fastchat/eval/eval_gpt_review.py""" import argparse import json import os import time import openai import tqdm import ray import shortuuid import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__n...
[ "prompt_template", "system_prompt" ]
2024-01-10
kaistAI/SelFee
data_augmentation~call_openai_multiprocessing_flan.py
from concurrent.futures import ProcessPoolExecutor import argparse import multiprocessing import openai from time import sleep from random import random import nltk nltk.download('punkt') from nltk import tokenize import json import fcntl from typing import List import os from tenacity import ( retry, sto...
[ "Here is the answer:\nPLACEHOLDER\n", "Revise the answer based on your own critique with minimal edits. Your revision should be simple and clear, so do not add any rhetorics such as apology for the past mistake. Write as if the revised answer is the first try.\nRevision:", "Here is a revised proposed answer:\nP...
2024-01-10
kaistAI/SelFee
data_augmentation~call_openai_multiprocessing_alpaca.py
from concurrent.futures import ProcessPoolExecutor import argparse import multiprocessing import openai from time import sleep from random import random import nltk nltk.download('punkt') from nltk import tokenize import json import fcntl from typing import List import os from tenacity import ( retry, sto...
[ "Revise the answer based on your own critique within 500 words. Your revision should be simple and clear, so do not add any rhetorics such as apology for the past mistake. Write as if the revised answer is the first try.\nRevision:", "PLACEHOLDER", "PLACEHOLDERHere is a proposed answer:\nPLACEHOLDER\n\nAre ther...
2024-01-10
Neelesh99/KnowledgeSpaces
LLMServer~construct_index.py
import os from llama_index import VectorStoreIndex, LLMPredictor, PromptHelper, Document, \ StringIterableReader, SlackReader, LangchainEmbedding, ServiceContext from langchain import HuggingFaceHub, HuggingFacePipeline from langchain.chat_models import ChatOpenAI from langchain.embeddings import HuggingFaceEmbedd...
[]
2024-01-10
MikeRock51/african_cuisines_recipe_api
models~chat~chatProvider.py
#!/usr/bin/env python3 from openai import OpenAI import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI key missing") client = OpenAI(api_key=api_key) def getChatResponse(chatHistory): try: completion = client.chat.comp...
[]
2024-01-10
MikeRock51/african_cuisines_recipe_api
chatbot~yishu_cli.py
#!/usr/bin/env python3 from openai import OpenAI from termcolor import colored import os # Load environment variables from a .env file from dotenv import load_dotenv load_dotenv() api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI key missing") client = OpenAI(api_key=api_key) def m...
[ "Your name is Yishu. You are a food and nutrition specialist bot. You provide expert assistance on all matters related to food, nutrition and health" ]
2024-01-10
goldenNormal/meeting-summary
utils_llm_models.py
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.schema import ( HumanMessage, AIMessage, SystemMessage ) import time import os OPENAI_API_KEY,API_BASE = os.getenv('OPENAI_API_KEY'),os.getenv('API_BASE') from langchain.chat_models import ChatOpenAI from jinja2 i...
[]
2024-01-10
jhmatthews/alpro
alpro~models.py
import numpy as np from scipy.interpolate import interp1d import types import os from scipy.integrate import simps class units: ''' class containing some units. Should probably use astropy units but I find them a bit annoying. ''' def __init__(self): self.kpc = 3.0857e21 self.pc =...
[]
2024-01-10
gpt4plugins/autogen
test~test_code.py
import sys import os import pytest import autogen from autogen.code_utils import ( UNKNOWN, extract_code, execute_code, infer_lang, improve_code, improve_function, ) KEY_LOC = "notebook" OAI_CONFIG_LIST = "OAI_CONFIG_LIST" here = os.path.abspath(os.path.dirname(__file__)) # def test_find_code...
[]
2024-01-10
Sunbird-VA/sakhi_api_service
jadupitara_ingest_data.py
import requests import json import os.path import openai from gpt_index import SimpleDirectoryReader from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.docstore.document import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import Recur...
[ "['Collection']", "contentType" ]
2024-01-10
Sunbird-VA/sakhi_api_service
query_with_langchain.py
import logging import openai from gpt_index import SimpleDirectoryReader from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.docstore.document import Document from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter fr...
[ "question", "[]", "[PLACEHOLDER, PLACEHOLDER]", "\n Write the same question as user input and make it more descriptive without adding new information and without making the facts incorrect.\n\n User: {question}\n Rephrased User input:" ]
2024-01-10
BoChenGroup/PyDPM
pydpm~metric~topic_coherence.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: Xinyang Liu <lxy771258012@163.com> # License: BSD-3-Clause import numpy as np from gensim.test.utils import common_corpus, common_dictionary from gensim.models.coherencemodel import CoherenceModel """ Examples --------- One way of using this feature is through prov...
[]
2024-01-10
dlt-hub/qdrant_dlt_rag
unstructured_to_qdrant.py
import getpass import os from dotenv import load_dotenv load_dotenv() OPENAI_API_KEY= os.getenv("OPENAI_API_KEY") import os import logging from typing import Dict, List # Configure logging logging.basicConfig(level=logging.INFO) from langchain.document_loaders import TextLoader from langchain.embeddings.openai impo...
[]
2024-01-10
dlt-hub/qdrant_dlt_rag
ragas_custom.py
"""An implementation of the Ragas metric """ from deepeval.metrics import BaseMetric from deepeval.test_case import LLMTestCase import warnings class ContextualPrecisionMetric(BaseMetric): """This metric checks the contextual precision using Ragas""" def __init__( self, minimum_score: float =...
[]
2024-01-10
dlt-hub/qdrant_dlt_rag
evals.py
import logging from typing import Dict, Tuple, Optional from openai import OpenAI from ragas_custom import RagasMetric from deepeval.test_case import LLMTestCase from dotenv import load_dotenv load_dotenv() import os OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") client = OpenAI(api_key=OPENAI_API_KEY) from qdrant_cl...
[ "You are a helpful assistant." ]
2024-01-10
nik-55/learning-ml
ml-3~pdf-project~answer.py
from langchain.prompts import PromptTemplate from pypdf import PdfReader from langchain.vectorstores import FAISS from langchain.embeddings import HuggingFaceEmbeddings from langchain.llms import HuggingFaceHub from langchain.chains import LLMChain, ConversationalRetrievalChain from langchain.text_splitter import Chara...
[ "Give the answer to the question: {question} based on the following text: {content}" ]
2024-01-10
AlekHesa/Function_Call
db_sampling.py
import openai import os import requests from tenacity import retry,wait_random_exponential,stop_after_attempt from termcolor import colored from dotenv import dotenv_values import sqlite3 GPT_MODEL = "gpt-3.5-turbo-0613" config = dotenv_values(".env") openai.api_key= config['OPENAI_API_KEY'] @retry(wait=wait_rando...
[ "Query: PLACEHOLDER\n the previous query received the error PLACEHOLDER.\n Please return a fixed SQL query in plain text.\n Your response should consist of only the sql query with the separator sql_start at the beginning and sql_end at the end\n ...
2024-01-10
Slice-Labs/hackathon-2020-reddit-nlp
topics.py
import numpy as np import gensim.corpora as corpora from gensim.models import CoherenceModel from gensim.models import ldamulticore import multiprocessing as mp DEFAULT_WORKERS = max(1, mp.cpu_count() - 1) def create_id2word(tokenized_docs, filter_no_below=10, filter_no_above=0.5): id2word = corpora.Dictionary(to...
[]
2024-01-10
aidanandrews22/Lecture-Recorder
Lecture~src~window.py
from gi.repository import Gtk from .gi_composites import GtkTemplate import openai from openai import OpenAI() from google.cloud import speech from google.cloud import language_v1 from google.cloud import texttospeech from pydub import AudioSegment from pydub.playback import play from datetime import datetime import...
[ "You are a helpful assistant for Aidan. Your task is to correct any spelling discrepancies in the transcribed text. Only add necessary punctuation such as periods, commas, and capitalization, and use only the context provided. You can not generate text based on the input, you may only correct the input punctuationa...
2024-01-10
riccardobl/chat-jme
ingest~indexbuilder.py
import os from langchain.docstore.document import Document from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores.faiss import FAISS from langchain.embeddings.openai import OpenAIEmbeddings from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.llms import ...
[]
2024-01-10
riccardobl/chat-jme
query~discoursequery.py
import os,json import hashlib from langchain.docstore.document import Document import requests import markdownify from langchain import OpenAI, PromptTemplate, LLMChain from langchain.text_splitter import CharacterTextSplitter from langchain.chains.mapreduce import MapReduceChain from langchain.prompts import PromptTe...
[]
2024-01-10
riccardobl/chat-jme
TorchEmbeddings.py
from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env from sentence_transformers import SentenceTransformer, models import torch import numpy as np import threading from torch...
[]
2024-01-10
riccardobl/chat-jme
Summary.py
from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.lsa import LsaSummarizer as Summarizer from sumy.nlp.stemmers import Stemmer from sumy.utils import get_stop_words from bs4 import BeautifulSoup import gc import mi...
[]
2024-01-10
riccardobl/chat-jme
bot.py
import os import utils import traceback from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.chains import ConversationChain from langchain.llms import OpenAI import langchain from langchain.cache import InMemoryCache from langchain.llms import OpenAI from langchain.chains.conversati...
[ "prompts/openai.text-davinci-003.txt", "question", "prompts/PLACEHOLDER.PLACEHOLDER.txt" ]
2024-01-10
riccardobl/chat-jme
SmartCache.py
from langchain.cache import BaseCache import os import utils from embeddings import EmbeddingsManager import json from typing import Any, Dict, List, Optional, Tuple from langchain.schema import Generation import time import pickle from Summary import Summary import uuid RETURN_VAL_TYPE = List[Generation] cla...
[]
2024-01-10
riccardobl/chat-jme
OpenAICachedEmbeddings.py
"""Wrapper around OpenAI embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env from langchain.embeddings.openai import OpenAIEmbeddings from typing i...
[]
2024-01-10
riccardobl/chat-jme
ingest~website.py
#Ingest website pages import requests from bs4 import BeautifulSoup import hashlib from langchain.docstore.document import Document import time from . import indexbuilder class Website(indexbuilder.IndexBuilder): def __init__(self,config,options): super().__init__(config,options) self.index=[ ...
[]
2024-01-10
riccardobl/chat-jme
ingest~source.py
# Clone the repo and ingest all the java and markdown files import hashlib from langchain.docstore.document import Document import os import re from . import indexbuilder import time class Source(indexbuilder.IndexBuilder) : def __init__(self,config,options,githubRepo, branch,includeFiles): super().__init__...
[]
2024-01-10
zwssunny/chatgpt-on-wechat
voice~factory.py
""" voice factory """ def create_voice(voice_type): """ create a voice instance :param voice_type: voice type code :return: voice instance """ if voice_type == "baidu": from voice.baidu.baidu_voice import BaiduVoice return BaiduVoice() elif voice_type == "google": ...
[]
2024-01-10
rkaganda/minecraft_explore_bot
observe_bot.py
from javascript import require, On, Once, AsyncTask, once, off import math import logging import json import bot_functions import bot_tasks import config import db from db import BotDB import openai # logger init logger = logging.getLogger('bot') logger.setLevel(logging.DEBUG) handler = logging.FileHandler(filename=c...
[ "heard - PLACEHOLDER", "PLACEHOLDER spawned", "digging completed.", "goal reached.", "processing task...", "can't see target" ]
2024-01-10
pytorch/vision
torchvision~datasets~country211.py
from pathlib import Path from typing import Callable, Optional from .folder import ImageFolder from .utils import download_and_extract_archive, verify_str_arg class Country211(ImageFolder): """`The Country211 Data Set <https://github.com/openai/CLIP/blob/main/data/country211.md>`_ from OpenAI. This dataset ...
[]
2024-01-10
Siddhartha90/The-Aubergine-index
sentimentAnalysis.py
import openai import os, json openai.api_key = os.environ.get("OPENAI_API_KEY") def sentimentAnalysis(reviews, keyword): # reviews = """ # 0: Loved it!! Awesome service. The food was so good that I didn't have time to take too many pictures. The service was impeccable and very attentive. It was overall a very din e...
[ "You are answering questions on the following reviews```PLACEHOLDER```", "Given this keyword ```PLACEHOLDER, Reply with how the related sentiment is for the given result. Use lateral thinking, for example, if it's implied all they sell is steak, that's probably gluten free", "[10]", "You are an assistant that...
2024-01-10
pilievwm/desc
category.py
import json import time import openai from collections import defaultdict import requests import validators from helpers import * import time import re import html import textwrap from bs4 import BeautifulSoup from request_counter import count_requests, global_counter, get from datetime import datetime from flask_socke...
[ "The output must be a coherent and detailed description of the category in question in strictly and valid HTML format. It should be written in PLACEHOLDER. The output should contains valid HTML code except tags like H1, newline, body and other main tags.For the headings use H3 and before each heading add one additi...
2024-01-10
smallv0221/datasets
datasets~openwebtext~openwebtext.py
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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/lice...
[]
2024-01-10
sbyebss/monge_map_solver
src~models~img2text_model.py
import torch from dalle2_pytorch import OpenAIClipAdapter from dalle2_pytorch.dalle2_pytorch import l2norm from dalle2_pytorch.optimizer import get_optimizer from torchmetrics.classification.accuracy import Accuracy import wandb from src.models.base_model import BaseModule from src.viz.points import plot_histogram tr...
[]
2024-01-10
sbyebss/monge_map_solver
src~models~text2img_model.py
import os import cv2 import torch from dalle2_pytorch import OpenAIClipAdapter from dalle2_pytorch.dalle2_pytorch import l2norm from dalle2_pytorch.optimizer import get_optimizer from PIL import Image, ImageDraw, ImageFont from torchvision.utils import make_grid, save_image from src.callbacks.txt2img_callbacks import...
[]
2024-01-10
gucky92/Auto-GPT
tests~integration~conftest.py
import os import openai.api_requestor import pytest from pytest_mock import MockerFixture from tests.conftest import PROXY from tests.vcr.vcr_filter import before_record_request, before_record_response BASE_VCR_CONFIG = { "record_mode": "new_episodes", "before_record_request": before_record_request, "bef...
[]
2024-01-10
norrishuang/private-llm-qa-bot
doc_preprocess~QA_auto_generator.py
import os import re import argparse import openai import json from tqdm import tqdm from langchain.document_loaders import PyPDFLoader from langchain.text_splitter import MarkdownTextSplitter from langchain.text_splitter import RecursiveCharacterTextSplitter # you need to install these packages: pypdf, tqdm, openai, l...
[ "\nHere is one page of {product}'s manual document\n```\n{page}\n```\nPlease automatically generate as many questions as possible based on this manual document, and follow these rules:\n1. \"{product}\"\" should be contained in every question\n2. questions start with \"Question:\"\n3. answers begin with \"Answer:\"...
2024-01-10
norrishuang/private-llm-qa-bot
deploy~lambda~intention~intention.py
import json import os import logging from langchain.embeddings import SagemakerEndpointEmbeddings from langchain.embeddings.sagemaker_endpoint import EmbeddingsContentHandler from langchain.vectorstores import OpenSearchVectorSearch from langchain.llms.sagemaker_endpoint import LLMContentHandler from langchain import ...
[ "Q: ", "instruction", "ๅ›ž็ญ”ไธ‹ๅˆ—้€‰ๆ‹ฉ้ข˜๏ผš\n\nPLACEHOLDER\n\n\"Q: \"PLACEHOLDER\"๏ผŒ่ฟ™ไธช้—ฎ้ข˜็š„ๆ้—ฎๆ„ๅ›พๆ˜ฏๅ•ฅ๏ผŸๅฏ้€‰้กน[PLACEHOLDER]\nA: ", "options", "{instruction}\n\n{fewshot}\n\n\"Q: \"{query}\"๏ผŒ่ฟ™ไธช้—ฎ้ข˜็š„ๆ้—ฎๆ„ๅ›พๆ˜ฏๅ•ฅ๏ผŸๅฏ้€‰้กน[{options}]\nA: " ]
2024-01-10
norrishuang/private-llm-qa-bot
code~intention_detect~intention.py
import json import os import logging from langchain.embeddings import SagemakerEndpointEmbeddings from langchain.embeddings.sagemaker_endpoint import EmbeddingsContentHandler from langchain.vectorstores import OpenSearchVectorSearch from langchain.llms.sagemaker_endpoint import LLMContentHandler from langchain import ...
[ "Q: ", "instruction", "ๅ›ž็ญ”ไธ‹ๅˆ—้€‰ๆ‹ฉ้ข˜๏ผš\n\nPLACEHOLDER\n\n\"Q: \"PLACEHOLDER\"๏ผŒ่ฟ™ไธช้—ฎ้ข˜็š„ๆ้—ฎๆ„ๅ›พๆ˜ฏๅ•ฅ๏ผŸๅฏ้€‰้กน[PLACEHOLDER]\nA: ", "options", "{instruction}\n\n{fewshot}\n\n\"Q: \"{query}\"๏ผŒ่ฟ™ไธช้—ฎ้ข˜็š„ๆ้—ฎๆ„ๅ›พๆ˜ฏๅ•ฅ๏ผŸๅฏ้€‰้กน[{options}]\nA: " ]
2024-01-10
norrishuang/private-llm-qa-bot
code~aos_write_job.py
#!/usr/bin/env python # coding: utf-8 from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth, helpers import boto3 import random import json from awsglue.utils import getResolvedOptions import sys import hashlib import datetime import re import os import itertools from bs4 import BeautifulSoup fr...
[ "0" ]
2024-01-10
Bhardwaj-python/J.A.R.V.I.S.
J.A.R.V.I.S~Brain~AIBrain.py
import openai fileopen = open("D:\\Bhardwaj\\J.A.R.V.I.S\\Data\\Api.txt") API = fileopen.read() fileopen.close() def ReplyBrain(question, chat_log=None): file_path = "D:\\Bhardwaj\\J.A.R.V.I.S\\Database\\chat_log.txt" with open(file_path, "r") as file: chat_log_template = file.read() if chat_log ...
[ "PLACEHOLDER You : PLACEHOLDER\nJ.A.R.V.I.S. : " ]
2024-01-10
Bhardwaj-python/J.A.R.V.I.S.
J.A.R.V.I.S~Brain~Qna.py
#Api Key fileopen = open("D:\\Bhardwaj\\J.A.R.V.I.S\\Data\\Api.txt") API = fileopen.read() fileopen.close() #Modules import openai #Coding openai.api_key = API completion = openai.Completion() def QuestionAnswer(question, chat_log=None): file_path = "D:\\Bhardwaj\\J.A.R.V.I.S\\Database\\chat_log.txt" with o...
[ "PLACEHOLDER You : PLACEHOLDER\nJ.A.R.V.I.S. : " ]
2024-01-10
emrgnt-cmplxty/quantgpt
quantgpt~core~data~cache.py
import logging import os import pickle import time from enum import Enum from typing import Any import openai from quantgpt.financial_tools.utils import home_path logger = logging.getLogger(__name__) class DataCache: def __init__( self, cache_file=None, initial_prompt_file=None, ...
[ "You are Bloomberg GPT, a Large Language Model which specializes in understanding financial data." ]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~central_intelligence.py
import logging from repo_gpt.agents.base_agent import BaseAgent from repo_gpt.agents.code_writer import CodeWritingAgent from repo_gpt.agents.repo_comprehender import RepoUnderstandingAgent from repo_gpt.file_handler.generic_code_file_handler import PythonFileHandler from repo_gpt.openai_service import OpenAIService f...
[ "You are an expert software engineer writing code in a repository. The user gives you a plan detailing how the code needs to be updated. You implement the code changes using functions. Ask clarifying questions.", "You are an expert software engineer. You have a few helper agents that help you understand and write...
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~code_manager~code_processor.py
import logging from itertools import islice from typing import List import numpy as np import pandas as pd import tiktoken from tqdm import tqdm from ..console import verbose_print from ..file_handler.abstract_handler import ParsedCode from ..openai_service import OpenAIService, tokens_from_string logger = logging.g...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~simple_memory_store.py
import json import logging import openai import tiktoken from tenacity import ( # for exponential backoff retry, stop_after_attempt, wait_random_exponential, ) from repo_gpt.openai_service import num_tokens_from_messages, num_tokens_from_string class MemoryStore: summary_prompt = """*Briefly* summa...
[ "Finally, ...", "You are an expert technical writer.", "*Briefly* summarize this partial conversation about programming.\n Include less detail about older parts and more detail about the most recent messages.\n Start a new paragraph every time the topic changes!\n\n This is only part of a longer conver...
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~code_manager~code_manager.py
import logging import os import pickle from pathlib import Path import pandas as pd from tqdm import tqdm from ..console import verbose_print from ..openai_service import OpenAIService from .code_dir_extractor import CodeDirectoryExtractor from .code_processor import CodeProcessor logger = logging.getLogger(__name__...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~test_generator.py
import os import openai as openai from .code_manager.abstract_extractor import LanguageHandler from .openai_service import GPT_3_MODELS, GPT_4_MODELS, num_tokens_from_messages class TestGenerator: TEMPERATURE = 0.4 # temperature = 0 can sometimes get stuck in repetitive loops, so we use 0.4 def __init__( ...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~autogen~repo_qna.py
import logging import os import re from pathlib import Path import autogen import pytest from repo_gpt.agents.autogen.user_proxy_function_call_agent import ( UserProxyFunctionCallAgent, ) from repo_gpt.agents.repo_comprehender import get_relative_path_directory_structure from repo_gpt.code_manager.abstract_extrac...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~repo_comprehender.py
# Refactored RepoUnderstandingAgent using the ParentAgent import logging import os from pathlib import Path from pathspec import PathSpec from pathspec.patterns import GitWildMatchPattern from tqdm import tqdm from repo_gpt.agents.base_agent import BaseAgent from repo_gpt.file_handler.generic_code_file_handler import...
[ "You are an expert software engineer on a specific code repository. Users ask you how they can implement something in their codebase. You first use your tools to search and understand the codebase and then figure out how to implement the users' task in the repository.\n **DO NOT** communicate with the user direc...
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~code_writer.py
import logging from pathlib import Path from repo_gpt.agents.base_agent import BaseAgent from repo_gpt.file_handler.generic_code_file_handler import PythonFileHandler from repo_gpt.openai_service import OpenAIService from repo_gpt.search_service import SearchService logger = logging.getLogger(__name__) class CodeWr...
[ "You are an expert software engineer writing code in a repository. The user gives you a plan detailing how the code needs to be updated. You implement the code changes using functions. Ask clarifying questions.\n **DO NOT** respond to the user directly. Use the functions instead.\n ", "{'type': 'string', '...
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~autogen~user_proxy_function_call_agent.py
import json import logging import autogen try: from termcolor import colored except ImportError: def colored(x, *args, **kwargs): return x logger = logging.getLogger(__name__) class UserProxyFunctionCallAgent(autogen.UserProxyAgent): def __init__(self, *args, **kwargs): super().__init...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~vscode_prompt_service.py
import json from dataclasses import asdict, dataclass from enum import Enum from typing import Union from repo_gpt.openai_service import OpenAIService from repo_gpt.prompt_service import PromptService from repo_gpt.search_service import SearchService class Status(Enum): SUCCESS = "SUCCESS" ERROR = "ERROR" ...
[]
2024-01-10
shruti222patel/repo-gpt
src~repo_gpt~agents~base_agent.py
import inspect import json import logging from abc import ABC, abstractmethod import openai import tiktoken from tenacity import ( # for exponential backoff retry, stop_after_attempt, wait_random_exponential, ) from repo_gpt.agents.simple_memory_store import MemoryStore logger = logging.getLogger(__name...
[ "Continue" ]
2024-01-10
dborodin836/TF2-GPTChatBot
gui~log_window.py
import os import sys import time import tkinter as tk from tkinter.ttk import Checkbutton import openai import ttkbootstrap as ttk from ttkbootstrap import Style from services.chatgpt import send_gpt_completion_request from utils.bans import ban_player, list_banned_players, unban_player from utils.bot_state import st...
[ "gpt3 ", "Type your commands here... Or start with 'help' command" ]
2024-01-10
bhargavkakadiya/llm-app
app_html.py
import sys from langchain.llms import OpenAI from langchain.document_loaders import WebBaseLoader from langchain.chains.summarize import load_summarize_chain from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores.faiss import FAISS from langchain.embeddings import OpenAIEmbedding...
[ "You are an AI assistant for answering questions for the job post and advice users to assess job based on the description.\n You are given the following extracted parts of a webpage of job post and a question. Provide a conversational answer.\n If you don't know the answer, just say \"Hmm, I'm not sure.\" Don...
2024-01-10
bhargavkakadiya/llm-app
app_pdf.py
import sys from langchain.llms import OpenAI from langchain.document_loaders import UnstructuredPDFLoader from langchain.chains.summarize import load_summarize_chain # Load the document loader = UnstructuredPDFLoader(str(sys.argv[1])) data = loader.load() llm = OpenAI(temperature=0) chain = load_summarize_chain(llm, ...
[]
2024-01-10
joshmlove/pdfReaderAI
pdfReaderAI.py
import openai import pdfplumber import constants # Load the OpenAI API key openai.api_key = constants.APIKEY # Read your own data from the PDF file with pdfplumber.open('Josh_Love_Resume copy.pdf') as pdf: data = ' '.join(page.extract_text() for page in pdf.pages) # Function to use the OpenAI API to answer queri...
[ "PLACEHOLDER\n\nPLACEHOLDER" ]
2024-01-10
ankitrana2709/CS50
chat~chatter.py
import openai import os # Set up the OpenAI API key openai.api_key = "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" # Set up the initial conversation prompt conversation_prompt = "Hello, I'm a chatbot. Which article you want today?" # Set up the API parameters model_engine = "davinci" max_tokens = 150 # Star...
[ "Hello, I'm a chatbot. Which article you want today?\n\nUser: Write an article about PLACEHOLDER\nBot:", "Hello, I'm a chatbot. Which article you want today?", "conversation_prompt12842c18-8928-44a0-8550-527da9fe5a43\n\nUser: Write an article about PLACEHOLDER\nBot:" ]
2024-01-10
msuliot/open_ai_fine_tuning
full_automatic.py
import requests import time import openai import datetime import json import sys # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def validate_file(filename): try: with open(filename, 'r') as file: lines = file.readli...
[ "Where do I mail my check?", "You are a helpful and professional customer service representative" ]
2024-01-10
msuliot/open_ai_fine_tuning
step2_upload_file.py
import openai # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def main(): ft_file = openai.File.create(file=open("data.jsonl", "rb"), purpose='fine-tune') print(ft_file) print("Here is the training file id you need for Step 4 =...
[]
2024-01-10
msuliot/open_ai_fine_tuning
step5_model_validation.py
import openai import datetime # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def pretty_table(f): print(f"\n{'ID':<33} {'Created At':<22} {'Finished At':<22} {'Status':<13} {'Fine Tuned Model'} ") print('-' * 140) for job in f...
[]
2024-01-10
msuliot/open_ai_fine_tuning
cleanup.py
import openai # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def delete_file(file_id): try: openai.File.delete(file_id) print("File deleted successfully") except Exception as e: print("Error deleting file: ...
[]
2024-01-10
msuliot/open_ai_fine_tuning
step3_file_validation.py
import openai import datetime # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def pretty_table(f): print(f"\n{'ID':<33} {'Purpose':<20} {'Status':<12} {'Created At'}") print('-' * 88) for file in f['data']: created_at =...
[]
2024-01-10
msuliot/open_ai_fine_tuning
step4_create_finetuned_model.py
import openai # get keys from .env file import os from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv('OPENAI_API_KEY') def main(): ##### You will need to replace the TRAINING_FILE_ID with the one you got from the previous step. ft_job = openai.FineTuningJob.create(training_file="TRAINING...
[]