Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add OpenCode LLM, closes #1010

davidmezzettic48ecb30628e
diff --git a/docs/pipeline/llm/llm.md b/docs/pipeline/llm/llm.md
index ebfce046..cdca39b8 100644
--- a/docs/pipeline/llm/llm.md
+++ b/docs/pipeline/llm/llm.md
@@ -58,11 +58,14 @@ llm("Answer the following question...", defaultrole="user")
llm("Answer the following question...", defaultrole="prompt")
```
-The LLM pipeline automatically detects the underlying LLM framework. This can also be manually set.
+The LLM pipeline automatically detects the underlying LLM framework. This can also be manually set. The following methods are supported.
-[Hugging Face Transformers](https://github.com/huggingface/transformers), [llama.cpp](https://github.com/abetlen/llama-cpp-python) and [hosted API models via LiteLLM](https://github.com/BerriAI/litellm) are all supported by this pipeline.
+- [Hugging Face Transformers](https://github.com/huggingface/transformers)
+- [llama.cpp](https://github.com/abetlen/llama-cpp-python)
+- [LLM APIs via LiteLLM](https://github.com/BerriAI/litellm)
+- [OpenCode server](https://github.com/anomalyco/opencode)
-See the [LiteLLM documentation](https://litellm.vercel.app/docs/providers) for the options available with LiteLLM models. llama.cpp models support both local and remote GGUF paths on the HF Hub.
+`llama.cpp` models support both local and remote GGUF paths on the HF Hub. See the [LiteLLM documentation](https://litellm.vercel.app/docs/providers) for the options available with LiteLLM models. See the [OpenCode documentation](https://opencode.ai/docs/server/) for more on how to integrate the LLM pipeline with a running OpenCode instance.
```python
from txtai import LLM
@@ -87,9 +90,13 @@ llm = LLM("ollama/gpt-oss", api_base="http://localhost:11434")
llm = LLM("openai/gpt-oss", api_base="http://localhost:4000")
# LLM APIs - must also set API key via environment variable
-llm = LLM("gpt-5.1")
+llm = LLM("gpt-5.2")
llm = LLM("claude-opus-4-5-20251101")
llm = LLM("gemini/gemini-3-pro-preview")
+
+# Local OpenCode server started via `opencode serve`
+llm = LLM("opencode")
+llm = LLM("opencode/big-pickle", url="http://localhost:4000")
```
Models can be externally loaded and passed to pipelines. This is useful for models that are not yet supported by Transformers and/or need special initialization.
diff --git a/setup.py b/setup.py
index 71472f66..11ef9e98 100644
--- a/setup.py
+++ b/setup.py
@@ -75,7 +75,7 @@ extras["pipeline-data"] = ["beautifulsoup4>=4.9.3", "chonkie>=1.0.2", "docling>=
extras["pipeline-image"] = ["imagehash>=4.2.1", "pillow>=7.1.2", "timm>=0.4.12"]
-extras["pipeline-llm"] = ["litellm>=1.37.16", "llama-cpp-python>=0.2.75"]
+extras["pipeline-llm"] = ["httpx>=0.28.1", "litellm>=1.37.16", "llama-cpp-python>=0.2.75"]
extras["pipeline-text"] = ["gliner>=0.2.23", "sentencepiece>=0.1.91", "staticvectors>=0.2.0"]
diff --git a/src/python/txtai/pipeline/llm/factory.py b/src/python/txtai/pipeline/llm/factory.py
index 50e9e0a1..f89dce95 100644
--- a/src/python/txtai/pipeline/llm/factory.py
+++ b/src/python/txtai/pipeline/llm/factory.py
@@ -7,6 +7,7 @@ from ...util import Resolver
from .huggingface import HFGeneration
from .litellm import LiteLLM
from .llama import LlamaCpp
+from .opencode import OpenCode
class GenerationFactory:
@@ -36,6 +37,10 @@ class GenerationFactory:
if method == "llama.cpp":
return LlamaCpp(path, **kwargs)
+ # OpenCode generation
+ if method == "opencode":
+ return OpenCode(path, **kwargs)
+
# Hugging Face Transformers generation
if method == "transformers":
return HFGeneration(path, **kwargs)
@@ -61,6 +66,8 @@ class GenerationFactory:
method = "litellm"
elif LlamaCpp.ismodel(path):
method = "llama.cpp"
+ elif OpenCode.ismodel(path):
+ method = "opencode"
else:
method = "transformers"
diff --git a/src/python/txtai/pipeline/llm/opencode.py b/src/python/txtai/pipeline/llm/opencode.py
new file mode 100644
index 00000000..ad5b30c4
--- /dev/null
+++ b/src/python/txtai/pipeline/llm/opencode.py
@@ -0,0 +1,77 @@
+"""
+OpenCode module
+"""
+
+import httpx
+
+from transformers.utils import cached_file
+
+from .generation import Generation
+
+
+class OpenCode(Generation):
+ """
+ OpenCode generative model.
+ """
+
+ @staticmethod
+ def ismodel(path):
+ """
+ Checks if path is an OpenCode model.
+
+ Args:
+ path: input path
+
+ Returns:
+ True if this is an OpenCode model, False otherwise
+ """
+
+ return isinstance(path, str) and path.lower().startswith("opencode") and not OpenCode.ishub(path)
+
+ @staticmethod
+ def ishub(path):
+ """
+ Checks if path is available on the HF Hub.
+
+ Args:
+ input path
+
+ Returns:
+ True if this is a model on the HF Hub
+ """
+
+ # pylint: disable=W0702
+ try:
+ return cached_file(path_or_repo_id=path, filename="config.json") is not None if "/" in path else False
+ except:
+ return False
+
+ def __init__(self, path, template=None, **kwargs):
+ super().__init__(path, template, **kwargs)
+
+ # Get model and provider from path
+ self.provider, self.model = path.split("/", 1) if "/" in path else (None, None)
+
+ # Get base url, default to `opencode serve` default
+ self.url = kwargs.get("url", "http://localhost:4096")
+
+ # Start an OpenCode session
+ self.session = httpx.post(f"{self.url}/session").json()
+
+ def stream(self, texts, maxlength, stream, stop, **kwargs):
+ for text in texts:
+ # Build text string
+ text = "\n".join([x["content"] for x in text]) if isinstance(text, list) else text
+
+ # Add text to request
+ request = {"parts": [{"type": "text", "text": text}]}
+
+ # Optionally add model, if available
+ if self.model:
+ request["model"] = {"providerID": self.provider, "modelID": self.model}
+
+ # Submit request and read JSON response
+ response = httpx.post(f"{self.url}/session/{self.session['id']}/message", json=request, timeout=None).json()
+
+ # Transform JSON into a text response
+ yield "\n".join([part["text"] for part in response["parts"] if part["type"] == "text"])
diff --git a/test/python/testpipeline/testllm/testopencode.py b/test/python/testpipeline/testllm/testopencode.py
new file mode 100644
index 00000000..8e2f9494
--- /dev/null
+++ b/test/python/testpipeline/testllm/testopencode.py
@@ -0,0 +1,71 @@
+"""
+OpenCode module tests
+"""
+
+import json
+import unittest
+
+from http.server import HTTPServer, BaseHTTPRequestHandler
+from threading import Thread
+
+from txtai.pipeline import LLM
+
+
+class RequestHandler(BaseHTTPRequestHandler):
+ """
+ Test HTTP handler.
+ """
+
+ def do_POST(self):
+ """
+ POST request handler.
+ """
+
+ # Mock response
+ content = "application/json"
+ response = json.dumps({"id": "0", "parts": [{"type": "text", "text": "blue"}]})
+
+ # Encode response as bytes
+ response = response.encode("utf-8")
+
+ self.send_response(200)
+ self.send_header("content-type", content)
+ self.send_header("content-length", len(response))
+ self.end_headers()
+
+ self.wfile.write(response)
+ self.wfile.flush()
+
+
+class TestOpenCode(unittest.TestCase):
+ """
+ OpenCode tests.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Create mock http server.
+ """
+
+ cls.httpd = HTTPServer(("127.0.0.1", 8005), RequestHandler)
+
+ server = Thread(target=cls.httpd.serve_forever, daemon=True)
+ server.start()
+
+ @classmethod
+ def tearDownClass(cls):
+ """
+ Shutdown mock http server.
+ """
+
+ cls.httpd.shutdown()
+
+ def testGeneration(self):
+ """
+ Test generation with OpenCode
+ """
+
+ # Test model generation with LiteLLM
+ model = LLM("opencode/big-pickle", url="http://127.0.0.1:8005")
+ self.assertEqual(model("The sky is"), "blue")