Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix async #151

Merged
merged 2 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion libs/vertexai/langchain_google_vertexai/chains.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
from langchain_core.prompts import BasePromptTemplate, ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables import Runnable
from vertexai.generative_models._generative_models import ( # type: ignore
ToolConfig,
)

from langchain_google_vertexai.functions_utils import PydanticFunctionsOutputParser

Expand Down Expand Up @@ -50,7 +53,21 @@ def _create_structured_runnable_extra_step(
*,
prompt: Optional[BasePromptTemplate] = None,
) -> Runnable:
llm_with_functions = llm.bind(functions=functions)
names = [schema.schema()["title"] for schema in functions]
if hasattr(llm, "is_gemini_advanced") and llm._is_gemini_advanced: # type: ignore
llm_with_functions = llm.bind(
functions=functions,
tool_config={
"function_calling_config": {
"mode": ToolConfig.FunctionCallingConfig.Mode.ANY,
"allowed_function_names": names,
}
},
)
else:
llm_with_functions = llm.bind(
functions=functions,
)
parsing_prompt = ChatPromptTemplate.from_template(
"You are a world class algorithm for recording entities.\nMake calls "
"to the relevant function to record the entities in the following "
Expand Down
35 changes: 24 additions & 11 deletions libs/vertexai/langchain_google_vertexai/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _convert_to_parts(message: BaseMessage) -> List[Part]:
raw_content = [raw_content]
return [_convert_to_prompt(part) for part in raw_content]

vertex_messages = []
vertex_messages: List[Content] = []
convert_system_message_to_human_content = None
system_instruction = None
for i, message in enumerate(history):
Expand Down Expand Up @@ -431,6 +431,17 @@ def validate_environment(cls, values: Dict) -> Dict:
)
return values

@property
def _is_gemini_advanced(self) -> bool:
try:
if float(self.model_name.split("-")[1]) > 1.0:
return True
except ValueError:
pass
except IndexError:
pass
return False

def _generate(
self,
messages: List[BaseMessage],
Expand Down Expand Up @@ -722,7 +733,6 @@ async def _astream(
project=self.project,
convert_system_message_to_human=self.convert_system_message_to_human,
)
message = history_gemini.pop()
self.client = _get_client_with_sys_instruction(
client=self.client,
system_instruction=system_instruction,
Expand Down Expand Up @@ -868,15 +878,18 @@ class AnswerWithJustification(BaseModel):
parser = JsonOutputFunctionsParser()
name = schema["name"]

llm = self.bind(
functions=[schema],
tool_config={
"function_calling_config": {
"mode": ToolConfig.FunctionCallingConfig.Mode.ANY,
"allowed_function_names": [name],
}
},
)
if self._is_gemini_advanced:
llm = self.bind(
functions=[schema],
tool_config={
"function_calling_config": {
"mode": ToolConfig.FunctionCallingConfig.Mode.ANY,
"allowed_function_names": [name],
}
},
)
else:
llm = self.bind(functions=[schema])
if include_raw:
parser_with_fallback = RunnablePassthrough.assign(
parsed=itemgetter("raw") | parser, parsing_error=lambda _: None
Expand Down
2 changes: 1 addition & 1 deletion libs/vertexai/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.poetry]
name = "langchain-google-vertexai"

version = "0.1.3"
version = "1.0.1"
description = "An integration package connecting Google VertexAI and LangChain"
authors = []
readme = "README.md"
Expand Down
51 changes: 51 additions & 0 deletions libs/vertexai/tests/integration_tests/test_chains.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import Optional

import pytest
from langchain_core.messages import (
AIMessage,
)
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field

Expand Down Expand Up @@ -47,3 +50,51 @@ def test_create_structured_runnable_with_prompt() -> None:
)
res = chain.invoke({"class": "person", "attr": "age"})
assert isinstance(res, RecordPerson)


@pytest.mark.release
def test_reflection() -> None:
class Reflection(BaseModel):
reflections: str = Field(
description="The critique and reflections on the sufficiency, superfluency,"
" and general quality of the response"
)
score: int = Field(
description="Score from 0-10 on the quality of the candidate response.",
# gte=0,
# lte=10,
)
found_solution: bool = Field(
description="Whether the response has fully solved the question or task."
)

def as_message(self):
return AIMessage(
content=f"Reasoning: {self.reflections}\nScore: {self.score}"
)

@property
def normalized_score(self) -> float:
return self.score / 10.0

llm = ChatVertexAI(
model_name="gemini-1.5-pro-preview-0409",
)

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Reflect and grade the assistant response to the user question below.",
),
(
"user",
"Which planet is the closest to the Earth?",
),
("ai", "{input}"),
]
)

reflection_llm_chain = prompt | llm.with_structured_output(Reflection)
res = reflection_llm_chain.invoke({"input": "Mars"})
assert isinstance(res, Reflection)
2 changes: 0 additions & 2 deletions libs/vertexai/tests/integration_tests/test_chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ def test_vertexai_stream(model_name: str) -> None:
assert isinstance(chunk, AIMessageChunk)


@pytest.mark.xfail
@pytest.mark.release
async def test_vertexai_astream() -> None:
model = ChatVertexAI(temperature=0, model_name="gemini-pro")
Expand Down Expand Up @@ -144,7 +143,6 @@ def test_multimodal() -> None:


@pytest.mark.release
@pytest.mark.xfail(reason="problem on vertex side")
def test_multimodal_history() -> None:
llm = ChatVertexAI(model_name="gemini-pro-vision")
gcs_url = (
Expand Down
Loading