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

Gemini client #1953

Merged
merged 21 commits into from
Jul 3, 2024
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Fixed message formatting
  • Loading branch information
kevinmessiaen committed Jun 20, 2024
commit 216f6670635e2ca19e05051f64a73f989103ade4
31 changes: 29 additions & 2 deletions giskard/llm/client/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,34 @@
)


def _format(messages: Sequence[ChatMessage]) -> Sequence[ContentDict]:
system_prompts = []
content = []

for message in messages:
if message.role == "system":
system_prompts.append(message.content)

if len(content) == 0:
content.append(ContentDict(role="model", parts=[]))

content[0]["parts"].insert(0, f"# System:\n{message.content}")

continue

role = "model" if message.role == "assistant" else "user"

# Consecutive messages need to be grouped
last_message = None if len(content) == 0 else content[-1]
if last_message is not None and last_message["role"] == role:
last_message["parts"].append(message.content)
continue

content.append(ContentDict(role=message.role, parts=[message.content]))

return content


class GeminiClient(LLMClient):
def __init__(self, model: str = "gemini-pro", _client=None):
self.model = model
Expand All @@ -43,11 +71,10 @@ def complete(

if format:
warning(f"Unsupported format '{format}', ignoring.")
format = None

try:
completion = self._client.generate_content(
contents=[ContentDict(role=m.role, parts=m.content) for m in messages],
contents=_format(messages),
generation_config=genai.types.GenerationConfig(
temperature=temperature,
max_output_tokens=max_tokens,
Expand Down