A bridge to use Langchain output as an OpenAI-compatible API.
Project description
Langchain Openai API Bridge
🚀 Expose Langchain Agent (Langgraph) result as an OpenAI-compatible API 🚀
A FastAPI
+ Langchain
/ langgraph
extension to expose agent result as an OpenAI-compatible API.
Use any OpenAI-compatible UI or UI framework with your custom Langchain Agent
.
Support:
- ✅ Chat Completions API
- ✅ Invoke
- ✅ Stream
- ✅ Assistant API - Feature in progress
- ✅ Run Stream
- ✅ Threads
- ✅ Messages
- ✅ Run
- ✅ Tools step stream
- 🚧 Human In The Loop
If you find this project useful, please give it a star ⭐!
Table of Content
Quick Install
pip
pip install langchain-openai-api-bridge
poetry
poetry add langchain-openai-api-bridge
Usage
OpenAI Assistant API Compatible
# Assistant Bridge as OpenAI Compatible API
from langchain_openai_api_bridge.assistant import (
AssistantApp,
InMemoryMessageRepository,
InMemoryRunRepository,
InMemoryThreadRepository,
)
from langchain_openai_api_bridge.fastapi import include_assistant
assistant_app = AssistantApp(
thread_repository_type=InMemoryThreadRepository,
message_repository_type=InMemoryMessageRepository,
run_repository=InMemoryRunRepository,
agent_factory=MyAgentFactory,
)
api = FastAPI(
title="Langchain Agent OpenAI API Bridge",
version="1.0",
description="OpenAI API exposing langchain agent",
)
include_assistant(app=api, assistant_app=assistant_app, prefix="/assistant")
if __name__ == "__main__":
uvicorn.run(api, host="localhost")
# Agent Creation
@tool
def magic_number_tool(input: int) -> int:
"""Applies a magic function to an input."""
return input + 2
class MyAgentFactory(AgentFactory):
def create_agent(self, llm: BaseChatModel, dto: CreateLLMDto) -> CompiledGraph:
return create_react_agent(
llm,
[magic_number_tool],
messages_modifier="""You are a helpful assistant.""",
)
def create_llm(self, dto: CreateLLMDto) -> CompiledGraph:
return ChatOpenAI(
model=dto.model,
api_key=dto.api_key,
streaming=True,
temperature=dto.temperature,
)
Full example:
OpenAI Chat Completion API Compatible
# Server
from langchain_openai_api_bridge.assistant import (
AssistantApp,
InMemoryMessageRepository,
InMemoryRunRepository,
InMemoryThreadRepository,
)
from langchain_openai_api_bridge.fastapi import include_chat_completion
api = FastAPI(
title="Langchain Agent OpenAI API Bridge",
version="1.0",
description="OpenAI API exposing langchain agent",
)
api.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
assistant_app = AssistantApp(
thread_repository_type=InMemoryThreadRepository,
message_repository_type=InMemoryMessageRepository,
run_repository=InMemoryRunRepository,
agent_factory=MyAnthropicAgentFactory,
system_fingerprint="My System Fingerprint",
)
include_chat_completion(
app=api, assistant_app=assistant_app, prefix="/my-custom-path/anthropic"
)
# Client
openai_client = OpenAI(
base_url="http://my-server/my-custom-path/anthropic/openai/v1",
)
chat_completion = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": 'Say "This is a test"',
}
],
)
print(chat_completion.choices[0].message.content)
#> "This is a test"
Full example:
// Vercel AI sdk - example
// ************************
// app/api/my-chat/route.ts
import { NextRequest } from "next/server";
import { z } from "zod";
import { type CoreMessage, streamText } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
export const ChatMessageSchema = z.object({
id: z.string(),
role: z.string(),
createdAt: z.date().optional(),
content: z.string(),
});
const BodySchema = z.object({
messages: z.array(ChatMessageSchema),
});
export type AssistantStreamBody = z.infer<typeof BodySchema>;
const langchain = createOpenAI({
//baseURL: "https://my-project/my-custom-path/openai/v1",
baseURL: "http://localhost:8000/my-custom-path/openai/v1",
});
export async function POST(request: NextRequest) {
const { messages }: { messages: CoreMessage[] } = await request.json();
const result = await streamText({
model: langchain("gpt-4o"),
messages,
});
return result.toAIStreamResponse();
}
More Examples
More examples can be found in tests/test_functional
directory.
This project is not limited to OpenAI’s models; some examples demonstrate the use of Anthropic’s language models. Anthropic is just one example, and any LangChain-supported vendor is also supported by this library.
⚠️ Setup to run examples
Define OPENAI_API_KEY
or ANTHROPIC_API_KEY
on your system.
Examples will take token from environment variable or .env
at root of the project.
Contributing
If you want to contribute to this project, you can follow this guideline:
- Fork this project
- Create a new branch
- Implement your feature or bug fix
- Send a pull request
Installation
poetry install
poetry env use ./.venv/bin/python
Commands
Command | Command |
---|---|
Run Tests | poetry run pytest |
Limitations
-
Chat Completions Tools
- Functions cannot be passed through open ai API. Every functions need to be defined as a tool in langchain. Usage Example
-
LLM Usage Info
- Returned usage info is innacurate. This is due to a Langchain/Langgraph limitation where usage info isn't available when calling a Langgraph Agent.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for langchain_openai_api_bridge-0.3.6.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | d1897dbe2dae36049341c78e4706021119e3225932fe305bd79ca56b19be7d05 |
|
MD5 | 75934c98d534da6b852b47267e79691b |
|
BLAKE2b-256 | 2666781eb126bac65d1899ad43e76ed47fd960ffb6092a29b7b184a296fe9f06 |
Hashes for langchain_openai_api_bridge-0.3.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ff177b91b458a0c4b02a84a95b6c70369092ee08db592ff9abde248e5272bb84 |
|
MD5 | cdeafa5751e875b1e9e36e21925b1da0 |
|
BLAKE2b-256 | 169f800dcb512c9925249b57040a2e0a544f2ba4d2bd36eb4dc72186aa2266b8 |