Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
0xAlec committed Jul 6, 2023
0 parents commit be88bab
Show file tree
Hide file tree
Showing 15 changed files with 1,905 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
152 changes: 152 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello
Empty file added blacksmith/__init__.py
Empty file.
87 changes: 87 additions & 0 deletions blacksmith/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import redis
import json
import requests
from tenacity import retry, stop_after_attempt
from blacksmith.llm import llm_call
from blacksmith.defaults.prompts import DEFAULT_SYSTEM_PROMPT, DEFAULT_REACT_PROMPT

# Connect to tool storage service
# We should expose an SDK to create a client and manually retrieve tools if user has their own Agent implementation
r = redis.Redis(host="redis-service", port=6379)


class Agent:
def __init__(self, **kwargs) -> None:
type = kwargs.get("type", "zero-shot-react")

# Make this a switch case
if type == "zero-shot-react":
self.prompt = DEFAULT_REACT_PROMPT
self.system_prompt = DEFAULT_SYSTEM_PROMPT
else:
self.prompt = kwargs.get("prompt")
self.system_prompt = kwargs.get("system_prompt")

self.tools = kwargs.get(
"tools", [json.loads(tool.decode()) for tool in r.lrange("tools", 0, -1)]
)
self.max_loops = kwargs.get("max_loops", 5)

def process(self, messages, query):
func_calls = []

@retry(stop=stop_after_attempt(self.max_loops))
def _think():
resp = llm_call(messages=messages, tools=self.tools)

iterations = 0
while True:
print("Iteration ", iterations)
print(resp)

content = resp.get("content")
if content and ("Final Answer:" in content):
print(messages)
final_answer_index = content.index("Final Answer:") + len("Final Answer:")
final_answer = content[final_answer_index:].strip()
return final_answer

func = resp.get("function_call")
if func:
service_name = func["name"]
args = json.loads(func["arguments"])
url = f"http://{service_name}:80"
tool_res = requests.get(url=url, json=args)
data = tool_res.json()
print(f"Executed function {service_name}. Result: {data}")
func_calls.append(
{
"execution_order": iterations,
"function_name": {service_name},
"params": {func["arguments"]},
"result": {json.dumps(data)},
}
)
messages.append(
{
"role": "user",
"content": f"""
Result of {service_name} is {data}.
Generate an observation based on this result.
If you have enough information to answer {query}, return the final answer prefixed with 'Final Answer:'.
Otherwise, based on this observation, proceed with other function calls to gather information as appropriate.
""",
}
)
resp = llm_call(messages=messages, tools=self.tools)
iterations += 1

return _think(), func_calls

def run(self, input: str) -> None:
formatted_prompt = self.prompt.format(input=input)
messages = [
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": formatted_prompt},
]
return self.process(messages=messages, query=input)
23 changes: 23 additions & 0 deletions blacksmith/defaults/prompts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
DEFAULT_SYSTEM_PROMPT = """
**Instructions:**
1. Provide a clear and concise description of your question or request.
2. Include any relevant details or context that can help the model understand your prompt.
3. If applicable, specify the desired format or structure for the response.
4. Feel free to ask follow-up questions or provide additional instructions as needed.
**Prompt:**
"""

DEFAULT_REACT_PROMPT = """
Answer the following questions as best you can.
If the user demands a final answer but you are unsure, consider executing a function call to gather more information.
The result of all previous function calls will be added to the conversation history as an observation.
Begin!
Question: {input}
Decompose the question into multiple subquestions, and answer each one individually in order to arrive at the final answer.
"""
14 changes: 14 additions & 0 deletions blacksmith/llm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import openai
import os


# TODO: Only load functions if called from an "agent"
def llm_call(messages, tools):
MODEL = os.getenv("MODEL")
TEMPERATURE = int(os.getenv("TEMPERATURE"))
return openai.ChatCompletion.create(
model=MODEL,
messages=messages,
temperature=TEMPERATURE,
functions=tools,
)["choices"][0]["message"]
Empty file added blacksmith/scripts/__init__.py
Empty file.
87 changes: 87 additions & 0 deletions blacksmith/scripts/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import time
import argparse
import os
import shutil
from blacksmith.scripts.images import build_agent_images, build_tool_images
from blacksmith.scripts.k8s import (
create_k8s_manifest,
create_redis,
apply_k8s_manifest,
apply_redis,
remove,
)


def build_command(args):
# Create temporary build path
os.makedirs("./tmp")

print("🕵️‍♀️ Building agent images...")
agent_specs = build_agent_images()
print("✨ Completed!")
print("🛠️ Building tool images...")
tool_specs = build_tool_images()
print("✨ Completed!")

# Remove intermediate build files
shutil.rmtree("./tmp")

# Create k8s manifests
os.makedirs("./k8s")

# Clear existing manifest.yaml file
with open(f"./k8s/manifest.yaml", "w") as file:
file.write("")

print("📦 Creating manifest...")
create_k8s_manifest(agent_specs, tool_specs)
print("✨ Completed!")
print("⚙️ Building Redis tool registry...")
create_redis()
print("✨ Completed!")


def apply_command(args):
print("🚀 Deploying Redis tool registry...")
apply_redis()
print("✨ Deployment completed!")
print("🚀 Deploying agent and tools...")
time.sleep(2) # use a liveness probe here instead
apply_k8s_manifest()
print("✨ Deployment completed!")


def delete_command(args):
print("🚫 Deleting deployments...")
remove()
print("✅ Deployments deleted.")

# Remove k8s when done
shutil.rmtree("./k8s")


def main():
parser = argparse.ArgumentParser(prog="blacksmith")
subparsers = parser.add_subparsers(title="subcommands", dest="subcommand")

# Build step (images, manifest files)
build_parser = subparsers.add_parser("build", help="Build tools")
build_parser.set_defaults(func=build_command)

# Apply step (kubectl apply)
build_parser = subparsers.add_parser("apply", help="Apply")
build_parser.set_defaults(func=apply_command)

# Remove all deployments
build_parser = subparsers.add_parser("delete", help="Remove all deployments")
build_parser.set_defaults(func=delete_command)

args = parser.parse_args()
if hasattr(args, "func"):
args.func(args)
else:
parser.print_help()


if __name__ == "__main__":
main()
Loading

0 comments on commit be88bab

Please sign in to comment.