Skip to content

Commit 34d0a51

Browse files
authored
Merge pull request #136 from cagostino/chris/installation_target_testing
adjusting to have multiple installation methods so users can install …
2 parents f7b988b + 430435e commit 34d0a51

File tree

11 files changed

+122
-98
lines changed

11 files changed

+122
-98
lines changed

npcsh/conversation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77
from typing import Any, Dict, Generator, List
88
import os
99
import anthropic
10-
import ollama # Add to setup.py if missing
10+
1111
from openai import OpenAI
12-
from diffusers import StableDiffusionPipeline
1312
from google.generativeai import types
1413
import google.generativeai as genai
1514
from .npc_sysenv import get_system_message
@@ -34,6 +33,7 @@ def get_ollama_conversation(
3433
Returns:
3534
List[Dict[str, str]]: The list of messages in the conversation.
3635
"""
36+
import ollama
3737

3838
messages_copy = messages.copy()
3939
if messages_copy[0]["role"] != "system":

npcsh/embeddings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
NPCSH_EMBEDDING_PROVIDER,
1313
chroma_client,
1414
)
15-
import ollama
1615
from openai import OpenAI
1716
import anthropic
1817

@@ -21,6 +20,8 @@ def get_ollama_embeddings(
2120
texts: List[str], model: str = "nomic-embed-text"
2221
) -> List[List[float]]:
2322
"""Generate embeddings using Ollama."""
23+
import ollama
24+
2425
embeddings = []
2526
for text in texts:
2627
response = ollama.embeddings(model=model, prompt=text)

npcsh/image_gen.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import os
1111

1212
from openai import OpenAI
13-
from diffusers import StableDiffusionPipeline
1413

1514

1615
def generate_image_openai(
@@ -66,6 +65,8 @@ def generate_image_hf_diffusion(
6665
PIL.Image: The generated image.
6766
"""
6867
# Load the Stable Diffusion pipeline
68+
from diffusers import StableDiffusionPipeline
69+
6970
pipe = StableDiffusionPipeline.from_pretrained(model)
7071
pipe = pipe.to(device)
7172

npcsh/knowledge_graph.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
import datetime
44

55
import numpy as np
6-
import kuzu
6+
7+
try:
8+
import kuzu
9+
except ModuleNotFoundError:
10+
print("kuzu not installed")
711
from typing import Optional, Dict, List, Union, Tuple
812

913

@@ -581,7 +585,10 @@ def visualize_graph(conn):
581585
plt.show()
582586

583587

584-
import chromadb
588+
try:
589+
import chromadb
590+
except ModuleNotFoundError:
591+
print("chromadb not installed")
585592
import numpy as np
586593
import os
587594
import datetime

npcsh/llm_funcs.py

Lines changed: 16 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,17 @@
44
import os
55
import json
66
import PIL
7-
from PIL import Image
87

98
import sqlite3
109
from datetime import datetime
1110
from typing import List, Dict, Any, Optional, Union, Generator
12-
import typing_extensions as typing
13-
from pydantic import BaseModel, Field
14-
15-
import base64
16-
import re
17-
import io
1811

1912

2013
from jinja2 import Environment, FileSystemLoader, Template, Undefined
2114

2215
import pandas as pd
2316
import numpy as np
2417

25-
# chroma
26-
import chromadb
27-
from chromadb import Client
28-
29-
# llm providers
30-
import anthropic
31-
import ollama # Add to setup.py if missing
32-
from openai import OpenAI
33-
from diffusers import StableDiffusionPipeline
3418
from google.generativeai import types
3519
import google.generativeai as genai
3620

@@ -54,7 +38,6 @@
5438
NPCSH_API_URL,
5539
NPCSH_VISION_MODEL,
5640
NPCSH_VISION_PROVIDER,
57-
chroma_client,
5841
available_reasoning_models,
5942
available_chat_models,
6043
)
@@ -150,25 +133,30 @@ def generate_image(
150133
# image = generate_image_openai_like(prompt, model, npc.api_url, openai_api_key)
151134
elif provider == "diffusers":
152135
image = generate_image_hf_diffusion(prompt, model)
136+
else:
137+
image = None
153138
# save image
154139
# check if image is a PIL image
155140
if isinstance(image, PIL.Image.Image):
156141
image.save(filename)
157142
return filename
158143

159-
elif image is not None:
160-
# image is at a private url
161-
response = requests.get(image.data[0].url)
162-
with open(filename, "wb") as file:
163-
file.write(response.content)
164-
from PIL import Image
144+
else:
145+
try:
146+
# image is at a private url
147+
response = requests.get(image.data[0].url)
148+
with open(filename, "wb") as file:
149+
file.write(response.content)
150+
from PIL import Image
165151

166-
img = Image.open(filename)
167-
img.show()
168-
# console = Console()
169-
# console.print(Image.from_path(filename))
152+
img = Image.open(filename)
153+
img.show()
154+
# console = Console()
155+
# console.print(Image.from_path(filename))
156+
return filename
170157

171-
return filename
158+
except AttributeError as e:
159+
print(f"Error saving image: {e}")
172160

173161

174162
def get_embeddings(
@@ -511,7 +499,6 @@ def execute_llm_question(
511499
# messages.append({"role": "assistant", "content": output})
512500

513501
else:
514-
515502
response = get_conversation(
516503
messages,
517504
model=model,
@@ -1030,7 +1017,6 @@ def check_llm_command(
10301017
return {"messages": messages, "output": output}
10311018

10321019
elif action == "answer_question":
1033-
10341020
if ENTER_REASONING_FLOW:
10351021
print("entering reasoning flow")
10361022
result = enter_reasoning_human_in_the_loop(
@@ -1208,7 +1194,6 @@ def handle_tool_call(
12081194
# print(npc)
12091195
print("handling tool call")
12101196
if not npc:
1211-
12121197
print(
12131198
f"No tools available for NPC '{npc.name}' or tools_dict is empty. Available tools: {available_tools}"
12141199
)
@@ -1320,7 +1305,6 @@ def handle_tool_call(
13201305
print("Executing tool with input values:", input_values)
13211306

13221307
try:
1323-
13241308
tool_output = tool.execute(
13251309
input_values,
13261310
npc.all_tools_dict,
@@ -1335,7 +1319,6 @@ def handle_tool_call(
13351319
if "Error" in tool_output:
13361320
raise Exception(tool_output)
13371321
except Exception as e:
1338-
13391322
# diagnose_problem = get_llm_response(
13401323
## f"""a problem has occurred.
13411324
# Please provide a diagnosis of the problem and a suggested #fix.

npcsh/npc_sysenv.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from typing import Any
44
import os
55
import io
6-
import chromadb
76
import sqlite3
87
from dotenv import load_dotenv
98
from PIL import Image
@@ -222,7 +221,12 @@ def get_system_message(npc: Any) -> str:
222221

223222
EMBEDDINGS_DB_PATH = os.path.expanduser("~/npcsh_chroma.db")
224223

225-
chroma_client = chromadb.PersistentClient(path=EMBEDDINGS_DB_PATH)
224+
try:
225+
import chromadb
226+
227+
chroma_client = chromadb.PersistentClient(path=EMBEDDINGS_DB_PATH)
228+
except:
229+
chroma_client = None
226230

227231

228232
# Load environment variables from .env file

npcsh/response.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22
from pydantic import BaseModel
33
import os
44
import anthropic
5-
import ollama # Add to setup.py if missing
65
from openai import OpenAI
7-
from diffusers import StableDiffusionPipeline
86
from google.generativeai import types
97
from google import genai
108

@@ -143,6 +141,8 @@ def get_ollama_response(
143141
Returns:
144142
Dict[str, Any]: The response, optionally including updated messages.
145143
"""
144+
import ollama
145+
146146
# try:
147147
# Prepare the message payload
148148
system_message = get_system_message(npc) if npc else "You are a helpful assistant."

npcsh/search.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,12 @@ def rag_search(
162162
163163
"""
164164
if embedding_model is None:
165-
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
166-
165+
try:
166+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
167+
except:
168+
raise Exception(
169+
"Please install the sentence-transformers library to use this function or provide an embedding transformer model."
170+
)
167171
results = []
168172

169173
# Compute the embedding of the query

npcsh/shell_helpers.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,7 +1433,6 @@ def execute_slash_command(
14331433
command_parts, model=model, provider=provider, npc=npc, api_url=api_url
14341434
)
14351435
elif command_name == "help": # New help command
1436-
14371436
return {
14381437
"messages": messages,
14391438
"output": get_help(),
@@ -1763,7 +1762,7 @@ def execute_command(
17631762
messages: list = None,
17641763
conversation_id: str = None,
17651764
stream: bool = False,
1766-
embedding_model: Union[SentenceTransformer, Any] = None,
1765+
embedding_model=None,
17671766
):
17681767
"""
17691768
Function Description:
@@ -1774,7 +1773,7 @@ def execute_command(
17741773
db_path : str : Database path
17751774
npc_compiler : NPCCompiler : NPC compiler
17761775
Keyword Args:
1777-
embedding_model : Union[SentenceTransformer, Any] : Embedding model
1776+
embedding_model : Embedding model
17781777
current_npc : NPC : Current NPC
17791778
messages : list : Messages
17801779
Returns:
@@ -2086,7 +2085,7 @@ def execute_command_stream(
20862085
command: str,
20872086
db_path: str,
20882087
npc_compiler: NPCCompiler,
2089-
embedding_model: Union[SentenceTransformer, Any] = None,
2088+
embedding_model=None,
20902089
current_npc: NPC = None,
20912090
model: str = None,
20922091
provider: str = None,

npcsh/stream.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@
1010
from typing import Any, Dict, Generator, List
1111
import os
1212
import anthropic
13-
import ollama # Add to setup.py if missing
1413
from openai import OpenAI
15-
from diffusers import StableDiffusionPipeline
1614
from google import genai
1715

1816
from google.generativeai import types
@@ -53,6 +51,8 @@ def get_anthropic_stream(
5351
messages = messages[1:]
5452
elif npc is not None:
5553
system_message = get_system_message(npc)
54+
else:
55+
system_message = "You are a helpful assistant."
5656

5757
# Preprocess messages to ensure content is a list of dicts
5858
for message in messages:
@@ -274,6 +274,8 @@ def get_ollama_stream(
274274
**kwargs,
275275
) -> Generator:
276276
"""Streams responses from Ollama, supporting images and tools."""
277+
import ollama
278+
277279
messages_copy = messages.copy()
278280

279281
# Handle images if provided

0 commit comments

Comments
 (0)