flowmcp-pipeline 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flowmcp_pipeline-0.1.0/PKG-INFO +62 -0
- flowmcp_pipeline-0.1.0/README.md +17 -0
- flowmcp_pipeline-0.1.0/flowmcp/__init__.py +7 -0
- flowmcp_pipeline-0.1.0/flowmcp/cli.py +48 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/__init__.py +16 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/anthropic.py +43 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/base.py +99 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/gemini.py +66 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/groq.py +28 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/huggingface.py +25 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/mistral.py +28 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/ollama.py +33 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/openai.py +38 -0
- flowmcp_pipeline-0.1.0/flowmcp/llm/openai_compat.py +69 -0
- flowmcp_pipeline-0.1.0/flowmcp/mcp/__init__.py +3 -0
- flowmcp_pipeline-0.1.0/flowmcp/mcp/client.py +65 -0
- flowmcp_pipeline-0.1.0/flowmcp/pipeline.py +115 -0
- flowmcp_pipeline-0.1.0/flowmcp/rag/__init__.py +5 -0
- flowmcp_pipeline-0.1.0/flowmcp/rag/chunker.py +49 -0
- flowmcp_pipeline-0.1.0/flowmcp/rag/loader.py +171 -0
- flowmcp_pipeline-0.1.0/flowmcp/rag/retriever.py +84 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/PKG-INFO +62 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/SOURCES.txt +36 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/dependency_links.txt +1 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/entry_points.txt +2 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/requires.txt +39 -0
- flowmcp_pipeline-0.1.0/flowmcp_pipeline.egg-info/top_level.txt +1 -0
- flowmcp_pipeline-0.1.0/pyproject.toml +52 -0
- flowmcp_pipeline-0.1.0/setup.cfg +4 -0
- flowmcp_pipeline-0.1.0/tests/test_async_cleanup.py +58 -0
- flowmcp_pipeline-0.1.0/tests/test_batch.py +74 -0
- flowmcp_pipeline-0.1.0/tests/test_chunk_config.py +108 -0
- flowmcp_pipeline-0.1.0/tests/test_chunker.py +78 -0
- flowmcp_pipeline-0.1.0/tests/test_cli.py +21 -0
- flowmcp_pipeline-0.1.0/tests/test_openai_compat.py +161 -0
- flowmcp_pipeline-0.1.0/tests/test_pipeline.py +857 -0
- flowmcp_pipeline-0.1.0/tests/test_prompt_templates.py +125 -0
- flowmcp_pipeline-0.1.0/tests/test_url_loader.py +61 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flowmcp-pipeline
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple RAG + MCP + LLM pipeline framework — a clean alternative to LangChain
|
|
5
|
+
Author-email: SreejaPasula <sreejap974@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/SreejaPasula/flowmcp
|
|
8
|
+
Project-URL: Issues, https://github.com/SreejaPasula/flowmcp/issues
|
|
9
|
+
Keywords: rag,mcp,llm,ai,langchain-alternative,pipeline
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Provides-Extra: openai
|
|
17
|
+
Requires-Dist: openai>=1.0.0; extra == "openai"
|
|
18
|
+
Provides-Extra: anthropic
|
|
19
|
+
Requires-Dist: anthropic>=0.20.0; extra == "anthropic"
|
|
20
|
+
Provides-Extra: gemini
|
|
21
|
+
Requires-Dist: google-generativeai>=0.5.0; extra == "gemini"
|
|
22
|
+
Provides-Extra: mistral
|
|
23
|
+
Requires-Dist: mistralai>=1.0.0; extra == "mistral"
|
|
24
|
+
Provides-Extra: groq
|
|
25
|
+
Requires-Dist: groq>=0.9.0; extra == "groq"
|
|
26
|
+
Provides-Extra: huggingface
|
|
27
|
+
Requires-Dist: huggingface_hub>=0.20.0; extra == "huggingface"
|
|
28
|
+
Provides-Extra: pdf
|
|
29
|
+
Requires-Dist: pypdf>=4.0.0; extra == "pdf"
|
|
30
|
+
Provides-Extra: embeddings
|
|
31
|
+
Requires-Dist: sentence-transformers>=3.0.0; extra == "embeddings"
|
|
32
|
+
Provides-Extra: all
|
|
33
|
+
Requires-Dist: openai>=1.0.0; extra == "all"
|
|
34
|
+
Requires-Dist: anthropic>=0.20.0; extra == "all"
|
|
35
|
+
Requires-Dist: google-generativeai>=0.5.0; extra == "all"
|
|
36
|
+
Requires-Dist: mistralai>=1.0.0; extra == "all"
|
|
37
|
+
Requires-Dist: groq>=0.9.0; extra == "all"
|
|
38
|
+
Requires-Dist: huggingface_hub>=0.20.0; extra == "all"
|
|
39
|
+
Requires-Dist: pypdf>=4.0.0; extra == "all"
|
|
40
|
+
Requires-Dist: sentence-transformers>=3.0.0; extra == "all"
|
|
41
|
+
Provides-Extra: dev
|
|
42
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
43
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
44
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
45
|
+
|
|
46
|
+
# flowmcp
|
|
47
|
+
|
|
48
|
+
The simple way to build RAG + MCP + LLM pipelines. A clean alternative to LangChain.
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install flowmcp
|
|
52
|
+
pip install flowmcp[openai] # or [anthropic], [gemini], [pdf], ...
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from flowmcp import Pipeline
|
|
57
|
+
|
|
58
|
+
pipeline = Pipeline(llm="openai/gpt-4", docs="./my-docs")
|
|
59
|
+
print(pipeline.ask("What is our refund policy?"))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Full documentation: https://github.com/SreejaPasula/flowmcp
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# flowmcp
|
|
2
|
+
|
|
3
|
+
The simple way to build RAG + MCP + LLM pipelines. A clean alternative to LangChain.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install flowmcp
|
|
7
|
+
pip install flowmcp[openai] # or [anthropic], [gemini], [pdf], ...
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from flowmcp import Pipeline
|
|
12
|
+
|
|
13
|
+
pipeline = Pipeline(llm="openai/gpt-4", docs="./my-docs")
|
|
14
|
+
print(pipeline.ask("What is our refund policy?"))
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Full documentation: https://github.com/SreejaPasula/flowmcp
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
from .pipeline import Pipeline
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
7
|
+
parser = argparse.ArgumentParser(
|
|
8
|
+
prog="flowmcp",
|
|
9
|
+
description="Run flowmcp pipelines from the terminal.",
|
|
10
|
+
)
|
|
11
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
12
|
+
|
|
13
|
+
ask_parser = subparsers.add_parser(
|
|
14
|
+
"ask",
|
|
15
|
+
help="Ask a question using an LLM and optional documents.",
|
|
16
|
+
)
|
|
17
|
+
ask_parser.add_argument(
|
|
18
|
+
"--llm",
|
|
19
|
+
required=True,
|
|
20
|
+
help="LLM provider/model string (e.g., openai/gpt-4).",
|
|
21
|
+
)
|
|
22
|
+
ask_parser.add_argument(
|
|
23
|
+
"--docs",
|
|
24
|
+
default=None,
|
|
25
|
+
help="Path to document file or directory.",
|
|
26
|
+
)
|
|
27
|
+
ask_parser.add_argument(
|
|
28
|
+
"question",
|
|
29
|
+
help="Question to ask the pipeline.",
|
|
30
|
+
)
|
|
31
|
+
return parser
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main(argv=None) -> int:
|
|
35
|
+
parser = build_parser()
|
|
36
|
+
args = parser.parse_args(argv)
|
|
37
|
+
|
|
38
|
+
if args.command == "ask":
|
|
39
|
+
pipeline = Pipeline(llm=args.llm, docs=args.docs)
|
|
40
|
+
answer = pipeline.ask(args.question)
|
|
41
|
+
print(answer)
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
return 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
if __name__ == "__main__":
|
|
48
|
+
sys.exit(main())
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from .anthropic import AnthropicClient
|
|
2
|
+
from .base import LLM, LLMBase
|
|
3
|
+
from .gemini import GeminiClient
|
|
4
|
+
from .ollama import OllamaClient
|
|
5
|
+
from .openai import OpenAIClient
|
|
6
|
+
from .openai_compat import OpenAICompatClient
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"LLM",
|
|
10
|
+
"LLMBase",
|
|
11
|
+
"OpenAIClient",
|
|
12
|
+
"OpenAICompatClient",
|
|
13
|
+
"AnthropicClient",
|
|
14
|
+
"OllamaClient",
|
|
15
|
+
"GeminiClient",
|
|
16
|
+
]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from .base import LLMBase
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AnthropicClient(LLMBase):
|
|
5
|
+
def __init__(self, model: str):
|
|
6
|
+
self.model = model
|
|
7
|
+
try:
|
|
8
|
+
import anthropic
|
|
9
|
+
|
|
10
|
+
self.client = anthropic.Anthropic()
|
|
11
|
+
except ImportError:
|
|
12
|
+
raise ImportError("Install anthropic: pip install anthropic")
|
|
13
|
+
|
|
14
|
+
def complete(self, prompt: str) -> str:
|
|
15
|
+
message = self.client.messages.create(
|
|
16
|
+
model=self.model,
|
|
17
|
+
max_tokens=1024,
|
|
18
|
+
messages=[{"role": "user", "content": prompt}],
|
|
19
|
+
)
|
|
20
|
+
if message.usage:
|
|
21
|
+
self.last_usage = {
|
|
22
|
+
"prompt_tokens": message.usage.input_tokens,
|
|
23
|
+
"completion_tokens": message.usage.output_tokens,
|
|
24
|
+
"total_tokens": message.usage.input_tokens
|
|
25
|
+
+ message.usage.output_tokens,
|
|
26
|
+
}
|
|
27
|
+
return message.content[0].text
|
|
28
|
+
|
|
29
|
+
async def acomplete(self, prompt: str) -> str:
|
|
30
|
+
try:
|
|
31
|
+
import anthropic
|
|
32
|
+
except ImportError:
|
|
33
|
+
raise ImportError("Install anthropic: pip install anthropic")
|
|
34
|
+
client = anthropic.AsyncAnthropic()
|
|
35
|
+
try:
|
|
36
|
+
message = await client.messages.create(
|
|
37
|
+
model=self.model,
|
|
38
|
+
max_tokens=1024,
|
|
39
|
+
messages=[{"role": "user", "content": prompt}],
|
|
40
|
+
)
|
|
41
|
+
return message.content[0].text
|
|
42
|
+
finally:
|
|
43
|
+
await client.close()
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
import asyncio
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class LLMBase(ABC):
|
|
6
|
+
last_usage: dict = {}
|
|
7
|
+
|
|
8
|
+
@abstractmethod
|
|
9
|
+
def complete(self, prompt: str) -> str:
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
async def acomplete(self, prompt: str) -> str:
|
|
13
|
+
return await asyncio.to_thread(self.complete, prompt)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LLM:
|
|
17
|
+
"""
|
|
18
|
+
Factory for creating LLM clients from a simple string.
|
|
19
|
+
|
|
20
|
+
Supported formats:
|
|
21
|
+
"openai/gpt-4"
|
|
22
|
+
"openai-compat:local-model"
|
|
23
|
+
"anthropic/claude-3-5-sonnet"
|
|
24
|
+
"ollama/llama3"
|
|
25
|
+
"gemini/gemini-pro"
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def from_string(model_string: str, **kwargs) -> LLMBase:
|
|
30
|
+
if model_string.startswith("openai-compat:"):
|
|
31
|
+
provider = "openai-compat"
|
|
32
|
+
model = model_string.split(":", 1)[1].strip()
|
|
33
|
+
elif "/" in model_string:
|
|
34
|
+
provider, model = model_string.split("/", 1)
|
|
35
|
+
model = model.strip()
|
|
36
|
+
else:
|
|
37
|
+
raise ValueError(
|
|
38
|
+
f"Invalid model format '{model_string}'. "
|
|
39
|
+
"Use 'provider/model' e.g. 'openai/gpt-4' or 'openai-compat:<model>'"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
if not model:
|
|
43
|
+
raise ValueError(f"Missing model name in '{model_string}'.")
|
|
44
|
+
|
|
45
|
+
if provider == "openai-compat":
|
|
46
|
+
unexpected = set(kwargs) - {"base_url", "api_key"}
|
|
47
|
+
if unexpected:
|
|
48
|
+
bad = ", ".join(sorted(unexpected))
|
|
49
|
+
raise ValueError(
|
|
50
|
+
f"Unexpected keyword argument(s) for 'openai-compat': {bad}"
|
|
51
|
+
)
|
|
52
|
+
from .openai_compat import OpenAICompatClient
|
|
53
|
+
|
|
54
|
+
return OpenAICompatClient(
|
|
55
|
+
model,
|
|
56
|
+
base_url=kwargs.get("base_url"),
|
|
57
|
+
api_key=kwargs.get("api_key"),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
if kwargs:
|
|
61
|
+
bad = ", ".join(sorted(kwargs))
|
|
62
|
+
raise ValueError(
|
|
63
|
+
f"Unexpected keyword argument(s) for provider '{provider}': {bad}"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
if provider == "openai":
|
|
67
|
+
from .openai import OpenAIClient
|
|
68
|
+
|
|
69
|
+
return OpenAIClient(model)
|
|
70
|
+
elif provider == "anthropic":
|
|
71
|
+
from .anthropic import AnthropicClient
|
|
72
|
+
|
|
73
|
+
return AnthropicClient(model)
|
|
74
|
+
elif provider == "ollama":
|
|
75
|
+
from .ollama import OllamaClient
|
|
76
|
+
|
|
77
|
+
return OllamaClient(model)
|
|
78
|
+
elif provider == "gemini":
|
|
79
|
+
from .gemini import GeminiClient
|
|
80
|
+
|
|
81
|
+
return GeminiClient(model)
|
|
82
|
+
elif provider == "mistral":
|
|
83
|
+
from .mistral import MistralClient
|
|
84
|
+
|
|
85
|
+
return MistralClient(model)
|
|
86
|
+
elif provider == "groq":
|
|
87
|
+
from .groq import GroqClient
|
|
88
|
+
|
|
89
|
+
return GroqClient(model)
|
|
90
|
+
elif provider == "huggingface":
|
|
91
|
+
from .huggingface import HuggingFaceClient
|
|
92
|
+
|
|
93
|
+
return HuggingFaceClient(model)
|
|
94
|
+
else:
|
|
95
|
+
raise ValueError(
|
|
96
|
+
f"Unsupported provider '{provider}'. Supported: "
|
|
97
|
+
"openai, openai-compat, anthropic, ollama, gemini, "
|
|
98
|
+
"mistral, groq, huggingface"
|
|
99
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from .base import LLMBase
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GeminiClient(LLMBase):
|
|
7
|
+
"""
|
|
8
|
+
Google Gemini LLM client supporting both the modern `google-genai` SDK
|
|
9
|
+
and fallback to legacy `google-generativeai`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, model: str, api_key: Optional[str] = None):
|
|
13
|
+
self.model = model
|
|
14
|
+
self.api_key = (api_key or os.environ.get("GEMINI_API_KEY")
|
|
15
|
+
or os.environ.get("GOOGLE_API_KEY"))
|
|
16
|
+
|
|
17
|
+
def complete(self, prompt: str) -> str:
|
|
18
|
+
try:
|
|
19
|
+
import google.genai as genai
|
|
20
|
+
kwargs = {}
|
|
21
|
+
if self.api_key:
|
|
22
|
+
kwargs["api_key"] = self.api_key
|
|
23
|
+
client = genai.Client(**kwargs)
|
|
24
|
+
response = client.models.generate_content(model=self.model, contents=prompt)
|
|
25
|
+
if hasattr(response, "usage_metadata") and response.usage_metadata:
|
|
26
|
+
meta = response.usage_metadata
|
|
27
|
+
self.last_usage = {
|
|
28
|
+
"prompt_tokens": getattr(meta, "prompt_token_count", 0),
|
|
29
|
+
"completion_tokens": getattr(meta, "candidates_token_count", 0),
|
|
30
|
+
"total_tokens": getattr(meta, "total_token_count", 0),
|
|
31
|
+
}
|
|
32
|
+
return response.text
|
|
33
|
+
except ImportError:
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
import google.generativeai as genai_legacy
|
|
38
|
+
if self.api_key:
|
|
39
|
+
genai_legacy.configure(api_key=self.api_key)
|
|
40
|
+
model = genai_legacy.GenerativeModel(self.model)
|
|
41
|
+
response = model.generate_content(prompt)
|
|
42
|
+
if hasattr(response, "usage_metadata") and response.usage_metadata:
|
|
43
|
+
meta = response.usage_metadata
|
|
44
|
+
self.last_usage = {
|
|
45
|
+
"prompt_tokens": getattr(meta, "prompt_token_count", 0),
|
|
46
|
+
"completion_tokens": getattr(meta, "candidates_token_count", 0),
|
|
47
|
+
"total_tokens": getattr(meta, "total_token_count", 0),
|
|
48
|
+
}
|
|
49
|
+
return response.text
|
|
50
|
+
except ImportError:
|
|
51
|
+
raise ImportError("Install google-genai: pip install google-genai")
|
|
52
|
+
|
|
53
|
+
async def acomplete(self, prompt: str) -> str:
|
|
54
|
+
try:
|
|
55
|
+
import google.genai as genai
|
|
56
|
+
kwargs = {}
|
|
57
|
+
if self.api_key:
|
|
58
|
+
kwargs["api_key"] = self.api_key
|
|
59
|
+
client = genai.Client(**kwargs)
|
|
60
|
+
response = await client.aio.models.generate_content(model=self.model, contents=prompt)
|
|
61
|
+
return response.text
|
|
62
|
+
except (ImportError, AttributeError):
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
import asyncio
|
|
66
|
+
return await asyncio.to_thread(self.complete, prompt)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from .base import LLMBase
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GroqClient(LLMBase):
|
|
7
|
+
"""
|
|
8
|
+
Groq LLM client for fast inference using the groq Python SDK.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
llm = LLM.from_string("groq/llama3-8b-8192")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, model: str, api_key: Optional[str] = None):
|
|
15
|
+
self.model = model
|
|
16
|
+
self.api_key = api_key or os.environ.get("GROQ_API_KEY")
|
|
17
|
+
|
|
18
|
+
def complete(self, prompt: str) -> str:
|
|
19
|
+
try:
|
|
20
|
+
from groq import Groq
|
|
21
|
+
except ImportError:
|
|
22
|
+
raise ImportError("Install groq: pip install groq")
|
|
23
|
+
client = Groq(api_key=self.api_key)
|
|
24
|
+
response = client.chat.completions.create(
|
|
25
|
+
model=self.model,
|
|
26
|
+
messages=[{"role": "user", "content": prompt}]
|
|
27
|
+
)
|
|
28
|
+
return response.choices[0].message.content
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from .base import LLMBase
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class HuggingFaceClient(LLMBase):
|
|
7
|
+
"""
|
|
8
|
+
HuggingFace Inference API client for accessing hosted open-source models.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
llm = LLM.from_string("huggingface/mistralai/Mistral-7B-Instruct-v0.3")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, model: str, api_key: Optional[str] = None):
|
|
15
|
+
self.model = model
|
|
16
|
+
self.api_key = api_key or os.environ.get("HF_TOKEN")
|
|
17
|
+
|
|
18
|
+
def complete(self, prompt: str) -> str:
|
|
19
|
+
try:
|
|
20
|
+
from huggingface_hub import InferenceClient
|
|
21
|
+
except ImportError:
|
|
22
|
+
raise ImportError("Install huggingface_hub: pip install huggingface_hub")
|
|
23
|
+
client = InferenceClient(model=self.model, token=self.api_key)
|
|
24
|
+
response = client.text_generation(prompt, max_new_tokens=512)
|
|
25
|
+
return response
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from .base import LLMBase
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MistralClient(LLMBase):
|
|
7
|
+
"""
|
|
8
|
+
Mistral AI LLM client using the mistralai Python SDK.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
llm = LLM.from_string("mistral/mistral-small-latest")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, model: str, api_key: Optional[str] = None):
|
|
15
|
+
self.model = model
|
|
16
|
+
self.api_key = api_key or os.environ.get("MISTRAL_API_KEY")
|
|
17
|
+
|
|
18
|
+
def complete(self, prompt: str) -> str:
|
|
19
|
+
try:
|
|
20
|
+
from mistralai import Mistral
|
|
21
|
+
except ImportError:
|
|
22
|
+
raise ImportError("Install mistralai: pip install mistralai")
|
|
23
|
+
client = Mistral(api_key=self.api_key)
|
|
24
|
+
response = client.chat.complete(
|
|
25
|
+
model=self.model,
|
|
26
|
+
messages=[{"role": "user", "content": prompt}]
|
|
27
|
+
)
|
|
28
|
+
return response.choices[0].message.content
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from urllib.parse import urlparse
|
|
2
|
+
|
|
3
|
+
from .base import LLMBase
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class OllamaClient(LLMBase):
|
|
7
|
+
def __init__(self, model: str, base_url: str = "http://localhost:11434"):
|
|
8
|
+
parsed = urlparse(base_url)
|
|
9
|
+
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
10
|
+
raise ValueError(f"Invalid base_url '{base_url}'. Must start with http:// or https://")
|
|
11
|
+
self.model = model
|
|
12
|
+
self.base_url = base_url.rstrip("/")
|
|
13
|
+
|
|
14
|
+
def complete(self, prompt: str) -> str:
|
|
15
|
+
import urllib.request
|
|
16
|
+
import json
|
|
17
|
+
|
|
18
|
+
payload = json.dumps({"model": self.model, "prompt": prompt, "stream": False}).encode()
|
|
19
|
+
req = urllib.request.Request(
|
|
20
|
+
f"{self.base_url}/api/generate",
|
|
21
|
+
data=payload,
|
|
22
|
+
headers={"Content-Type": "application/json"}
|
|
23
|
+
)
|
|
24
|
+
with urllib.request.urlopen(req) as response:
|
|
25
|
+
data = json.loads(response.read())
|
|
26
|
+
prompt_tokens = data.get("prompt_eval_count", 0)
|
|
27
|
+
completion_tokens = data.get("eval_count", 0)
|
|
28
|
+
self.last_usage = {
|
|
29
|
+
"prompt_tokens": prompt_tokens,
|
|
30
|
+
"completion_tokens": completion_tokens,
|
|
31
|
+
"total_tokens": prompt_tokens + completion_tokens,
|
|
32
|
+
}
|
|
33
|
+
return data["response"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from .base import LLMBase
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class OpenAIClient(LLMBase):
|
|
5
|
+
def __init__(self, model: str):
|
|
6
|
+
self.model = model
|
|
7
|
+
try:
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
|
|
10
|
+
self.client = OpenAI()
|
|
11
|
+
except ImportError:
|
|
12
|
+
raise ImportError("Install openai: pip install openai")
|
|
13
|
+
|
|
14
|
+
def complete(self, prompt: str) -> str:
|
|
15
|
+
response = self.client.chat.completions.create(
|
|
16
|
+
model=self.model, messages=[{"role": "user", "content": prompt}]
|
|
17
|
+
)
|
|
18
|
+
if response.usage:
|
|
19
|
+
self.last_usage = {
|
|
20
|
+
"prompt_tokens": response.usage.prompt_tokens,
|
|
21
|
+
"completion_tokens": response.usage.completion_tokens,
|
|
22
|
+
"total_tokens": response.usage.total_tokens,
|
|
23
|
+
}
|
|
24
|
+
return response.choices[0].message.content
|
|
25
|
+
|
|
26
|
+
async def acomplete(self, prompt: str) -> str:
|
|
27
|
+
try:
|
|
28
|
+
from openai import AsyncOpenAI
|
|
29
|
+
except ImportError:
|
|
30
|
+
raise ImportError("Install openai: pip install openai")
|
|
31
|
+
client = AsyncOpenAI()
|
|
32
|
+
try:
|
|
33
|
+
response = await client.chat.completions.create(
|
|
34
|
+
model=self.model, messages=[{"role": "user", "content": prompt}]
|
|
35
|
+
)
|
|
36
|
+
return response.choices[0].message.content
|
|
37
|
+
finally:
|
|
38
|
+
await client.close()
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from urllib.parse import urlparse
|
|
4
|
+
|
|
5
|
+
from .base import LLMBase
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class OpenAICompatClient(LLMBase):
|
|
9
|
+
"""LLM client for OpenAI-compatible servers (LM Studio, vLLM, llama.cpp)."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
model: str,
|
|
14
|
+
base_url: Optional[str] = None,
|
|
15
|
+
api_key: Optional[str] = None,
|
|
16
|
+
):
|
|
17
|
+
resolved_url = (base_url or os.environ.get("OPENAI_BASE_URL") or "").strip()
|
|
18
|
+
parsed = urlparse(resolved_url)
|
|
19
|
+
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
20
|
+
raise ValueError(
|
|
21
|
+
"Invalid or missing base_url. Pass base_url or set OPENAI_BASE_URL "
|
|
22
|
+
"starting with http:// or https://."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
self.model = model
|
|
26
|
+
self.base_url = resolved_url.rstrip("/")
|
|
27
|
+
self.api_key = api_key or "none"
|
|
28
|
+
self.last_usage = {}
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
from openai import OpenAI
|
|
32
|
+
except ImportError:
|
|
33
|
+
raise ImportError("Install openai: pip install openai")
|
|
34
|
+
|
|
35
|
+
self.client = OpenAI(base_url=self.base_url, api_key=self.api_key)
|
|
36
|
+
|
|
37
|
+
def _record_usage(self, response) -> None:
|
|
38
|
+
usage = getattr(response, "usage", None)
|
|
39
|
+
if usage:
|
|
40
|
+
self.last_usage = {
|
|
41
|
+
"prompt_tokens": usage.prompt_tokens,
|
|
42
|
+
"completion_tokens": usage.completion_tokens,
|
|
43
|
+
"total_tokens": usage.total_tokens,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
def complete(self, prompt: str) -> str:
|
|
47
|
+
response = self.client.chat.completions.create(
|
|
48
|
+
model=self.model,
|
|
49
|
+
messages=[{"role": "user", "content": prompt}],
|
|
50
|
+
)
|
|
51
|
+
self._record_usage(response)
|
|
52
|
+
return response.choices[0].message.content
|
|
53
|
+
|
|
54
|
+
async def acomplete(self, prompt: str) -> str:
|
|
55
|
+
try:
|
|
56
|
+
from openai import AsyncOpenAI
|
|
57
|
+
except ImportError:
|
|
58
|
+
raise ImportError("Install openai: pip install openai")
|
|
59
|
+
|
|
60
|
+
client = AsyncOpenAI(base_url=self.base_url, api_key=self.api_key)
|
|
61
|
+
try:
|
|
62
|
+
response = await client.chat.completions.create(
|
|
63
|
+
model=self.model,
|
|
64
|
+
messages=[{"role": "user", "content": prompt}],
|
|
65
|
+
)
|
|
66
|
+
self._record_usage(response)
|
|
67
|
+
return response.choices[0].message.content
|
|
68
|
+
finally:
|
|
69
|
+
await client.close()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from typing import List, Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MCP:
|
|
5
|
+
"""
|
|
6
|
+
MCP (Model Context Protocol) client.
|
|
7
|
+
Connects to MCP servers and runs tools.
|
|
8
|
+
|
|
9
|
+
Example:
|
|
10
|
+
mcp = MCP(["filesystem", "github"])
|
|
11
|
+
result = mcp.run("List files in /src")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, tools: List[str]):
|
|
15
|
+
self.tools = tools
|
|
16
|
+
self._servers = {}
|
|
17
|
+
self._connect()
|
|
18
|
+
|
|
19
|
+
def _connect(self):
|
|
20
|
+
for tool in self.tools:
|
|
21
|
+
try:
|
|
22
|
+
self._servers[tool] = MCPServer(tool)
|
|
23
|
+
except Exception as e:
|
|
24
|
+
print(f"[flowmcp] Warning: Could not connect to MCP tool '{tool}': {e}")
|
|
25
|
+
|
|
26
|
+
def run(self, query: str) -> str:
|
|
27
|
+
results = []
|
|
28
|
+
for name, server in self._servers.items():
|
|
29
|
+
try:
|
|
30
|
+
result = server.execute(query)
|
|
31
|
+
if result:
|
|
32
|
+
results.append(f"[{name}]: {result}")
|
|
33
|
+
except Exception as e:
|
|
34
|
+
results.append(f"[{name}]: Error — {e}")
|
|
35
|
+
return "\n".join(results)
|
|
36
|
+
|
|
37
|
+
async def arun(self, query: str) -> str:
|
|
38
|
+
import asyncio
|
|
39
|
+
results = []
|
|
40
|
+
for name, server in self._servers.items():
|
|
41
|
+
try:
|
|
42
|
+
result = await asyncio.to_thread(server.execute, query)
|
|
43
|
+
if result:
|
|
44
|
+
results.append(f"[{name}]: {result}")
|
|
45
|
+
except Exception as e:
|
|
46
|
+
results.append(f"[{name}]: Error — {e}")
|
|
47
|
+
return "\n".join(results)
|
|
48
|
+
|
|
49
|
+
def list_tools(self) -> List[str]:
|
|
50
|
+
return list(self._servers.keys())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class MCPServer:
|
|
54
|
+
"""
|
|
55
|
+
Represents a connection to a single MCP server.
|
|
56
|
+
Contributors: implement specific MCP server integrations here.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, name: str):
|
|
60
|
+
self.name = name
|
|
61
|
+
|
|
62
|
+
def execute(self, query: str) -> Optional[str]:
|
|
63
|
+
# Contributors: add real MCP server communication here
|
|
64
|
+
# See: https://modelcontextprotocol.io/docs
|
|
65
|
+
return None
|